使用Rails 3.2删除连接表中的行

时间:2012-05-12 10:01:56

标签: ruby-on-rails ruby database

我有两个模型,用户和帐户,他们通过AccountUsers有多对多的关系。用户可以邀请其他用户访问他们的帐户,但我也希望经过身份验证的用户能够删除受邀用户(或协作者)。我只希望删除连接表中的关联或行,而不是用户对象。我不太清楚如何做到这一点,特别是我应该如何设置我的路由,破坏方法和link_to。

我的方法目前看起来像这样:

def destroy
    @account.users.delete(collaborator)
end

我的链接如下:

= link_to "Remove collaborator", collaborator,  confirm: "You sure?", :method => :delete

目前导致

undefined method `user_path' for #<#<Class:0x007fe3fc4f2378>:0x007fe3fe718510>

我还尝试将@account.users.delete(collaborator)直接放在我的link_to中,但它会在点击之前删除该行。

我的路线目前看起来像这样:

resources :accounts do
  resources :projects
  resources :invitations
  resources :collaborators, :only => [:index]
end

我的模特协会就像这样:

# User
has_many :account_users
has_many :accounts, through: :account_users, :dependent => :destroy

# Account
belongs_to :user
has_many :account_users
has_many :users, through: :account_users

如何以及如何才能实现我想要的目标?

我没有单独的控制器(协作者),我的销毁操作位于其中,它不在我的用户控制器中。

感谢。

1 个答案:

答案 0 :(得分:2)

当你有这个

时,问题可能出在路线上
 resources :collaborators, :only => [:index]

并且也嵌套在帐户中。所以你可以尝试重写一下routes.rb

resources :accounts do
  resources :projects
  resources :invitations
  resources :collaborators
end

,您的链接应如下所示

 = link_to 'Remove collaborator', accounts_colaborator_path(@account,@colaborator), :method => :delete