用于销毁两个ActiveRecord对象之间关系的Rails模式

时间:2016-12-24 17:40:23

标签: ruby-on-rails design-patterns activerecord model-view-controller

假设我有两个模型,A和B,每个模型与另一个模型has_and_belongs_to_many relationship。也就是说,一些A对象和B对象是“连接”的。

提供破坏这种关系的途径的正确方法是什么?因为我们没有破坏A或B,所以在A或B的控制器上进行破坏动作并没有多大意义。是否有某种标准方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

这就是我的所作所为:

<强>的routes.rb

resources :a do
  # use member or collection based on your needs
  member do
    # member creates a path like:
    # /a/[:id]/destroy_a_b
    delete :destroy_a_b
  end
# OR
  collection do
    # collection creates a path like:
    # /a/destroy_a_b
    delete :destroy_a_b
  end
end

然后在你的控制器中:

def destroy_a_b
   # with member you can do:
   @a =  A.find(params[:id])
   # but caution: you may not want to expose A outside of white-listed params

   # do your destruction
end

您可以在文档中阅读更多内容: http://guides.rubyonrails.org/routing.html#adding-more-restful-actions