1

假设我有两个模型A和B,其中每个模型都有一个has_and_belongs_to_many relationship与另一个。也就是说,一些A对象和B对象是“连接”的。用于破坏两个ActiveRecord对象之间关系的Rails模式

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

回答

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

+0

谢谢!这看起来不错,只是想知道,如果@a可以有很多b,我怎么能让路由包含被删除的b的id?(可能使用'member do'语法)。 – Nathan

相关问题