Anders
Anders

Reputation: 2941

Remove row in join table with Rails 3.2

I hav two models, User and Account, they have a many-to-many relationship through AccountUsers. Users can invite other Users to their account, but I would also like authenticated users to be able to remove invited users (or collaborators). I only want the association or the row in the join table to be deleted, not the user object. And I'm not quite sure how to do this, specifically how I should set up my routes, destroy method and link_to.

My method currently looks like this:

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

My link looks like this:

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

This currently results in

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

I have also tried to put @account.users.delete(collaborator)directly in my link_to, but the it deletes the row before it is being clicked.

My routes currently looks like this:

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

And my model association like this:

# 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

How and what should I do to be able to achieve what I want?

Not I have a separate controller (Collaborators) where my destroy action is located, it's not in my Users controller.

Thanks.

Upvotes: 0

Views: 348

Answers (1)

Suborx
Suborx

Reputation: 3669

The problem might be in routes when you have this

 resources :collaborators, :only => [:index]

and is also nested in accounts. So you can try rewrite the routes.rb a bit

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

and your link should look like this

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

Upvotes: 2

Related Questions