2014-01-27 22 views
0

我有Rails 4應用程序嵌套資源和子(會話)也有與另一個模型(揚聲器)多對多的關係。在哪裏把嵌套的資源刪除多對多

resources :parent do 
    resources :child 
end 

class Parent < ActiveRecord::Base 
    has_many :children 
end 

class Child < ActiveRecord::Base 
    belongs_to :parent 
    has_and_belongs_to_many :speakers 
end 

class Speaker < ActiveRecord::Base 
    has_and_belongs_to_many :children 
end 

我想弄清楚哪個控制器應該有關係(揚聲器)的刪除/添加。我可以在SessionController#destroy中處理這個問題,但是必須處理這種關係的特殊情況(感覺不對)。目前我有一個自定義路由到SessionController#speaker傳遞參數的操作(:add,:delete)。

我保持對關係的雙方的記錄,僅刪除關係

sessions.speakers.delete(speaker) 

你覺得是這樣做的最佳方法?

  • 請SessionController刪除關係中一種特殊的路由
  • 添加到SpeakerController在一種特殊的路由
  • 創建一個新的控制器來處理關係

回答

0

ActiveRecord的

要添加或刪除集合中的對象,您必須使用<< and .delete ActiveRecord方法

使用ActiveRecord對象這些工作,可以這樣調用:

#apps/controller/posts_controller.rb 
def comment 
    post = Post.find(params[:post_id]) 
    comment = Comment.find(params[:comment_id]) 

    #Add 
    post.comments << comment 

    #Delete 
    post.comments.delete(comment) 
end 

控制器

在回答你的問題,就是哪個控制器,我建議你保持代碼在「父」控制器(在你的情況下,sessions)&創建一個單一的方法來處理過程

下面是我們上週創建活動代碼:

#config/routes.rb 
resources :entries do 
    match ":category_id", to: :category, via: [:post, :delete], as: "category" 
end 

#app/controllers/entries_controller.rb 
def category 
    entry = Entry.find(params[:entry_id]) 
    category = Category.find(params[:category_id]) 

    #Actions 
    entry.categories << category if request.post? 
    entry.categories.delete(category) if request.delete? 

    #Return 
    redirect_to collection_path 
end 

這使我們能夠調用不同:method一個鏈接調用不同的操作:

<%= link_to "Add Category", admin_entry_category_path("60", "20"), method: :post %> 
+0

謝謝。我意識到刪除和<<。我喜歡你創建的路線,感覺比傳遞一個額外的參數更好,使用該方法來執行該動作。 – user3241602