Rails 4 Ajax:删除嵌套对象

时间:2015-10-15 13:24:14

标签: ruby-on-rails ajax ruby-on-rails-4 nested

我正在尝试删除项目页面上的“集合”。当我点击删除链接时,我收到此错误:

  

没有路线匹配[GET]“/ collections / 87”

我的错误在哪里?

我的文件:

的routes.rb

resources :projects do
  resources :collections, :except => [:update, :destroy]
end

resources :collections, :only => [:update, :destroy]

collection.rb

class Collection < ActiveRecord::Base
  belongs_to :project

  ...
  validates :project, presence: true
end

project.rb

class Project < ActiveRecord::Base

  has_many :collections, dependent: :destroy

  accepts_nested_attributes_for :collections, reject_if: proc() { | attrs | attrs[ 'title' ] .blank? }, allow_destroy: true

end

collections_controller.rb

class CollectionsController < ApplicationController
  ...

  respond_to :html, :js

  def destroy
    @project = @collection.project_id
    @collection.destroy

    respond_to do |format|
      format.html { redirect_to @project }
      format.js # render collections/destroy.js.erb
    end

  end

projects_controller.rb

class ProjectsController < ApplicationController

  ...

  respond_to :html, :js

  def index
    @projects = Project.all
    respond_with(@projects)
  end

  def show
    @collection = Collection.new
    @collections = @project.collections.order("title ASC")
  end

  def destroy
    @project.destroy
    respond_with(@project)
  end

...

/projects/show.html.erb

<% @collections.each do |collection| %>
  <%= link_to 'Destroy Collection', collection, method: :delete, remote: true %>
<% end %>

1 个答案:

答案 0 :(得分:0)

问题在于你的收藏控制器没有收到有问题的收藏。

改变可能是:

class CollectionsController < ApplicationController
  ...

  respond_to :html, :js

  def destroy
    @project = Project.find(params[:project_id])

    @project.collections.find(params[:id]).delete

    respond_to do |format|
      format.html { redirect_to @project }
      format.js # render collections/destroy.js.erb
    end

  end