0

I have a model Project which has_many excursions.

class Project < ActiveRecord::Base
  has_many :excursions

    def remove_user_from_excursion(excursion_id, current_user)
      excursions.find(excursion_id).users.delete(current_user)
      save!
    end
end

then I have a model Excursions which has_and_belongs_to_many_users users.

class Excursion < ActiveRecord::Base
  belongs_to :project
  has_and_belongs_to_many :users
end

I would like to provide the functionality to remove a user from an excursion, I have tried calling the remove_user_from_excursion method on the Project model and it does not seem to work. The user remains as part of the excursions. What am I doing wrong?

General_9
  • 2,249
  • 4
  • 28
  • 46

3 Answers3

0

First of all, you cannot use "find" on an array. In your case you are supposed to have an array of excursions and you want to find it by id which will not work this way. The "find" method works on the model class like "Excursion.find(excursion_id)".

Second, you must have an instance of "Project" to get the excursions that are associated with the project, so you should use "self" -> "self.excursions......

Eventually, to do what you want you could write something like the followig:

def remove_user_from_excursion(excursion_id, current_user)
    Excursion.find(excursion_id).users.delete(current_user)
end 

or

def remove_user_from_excursion(excursion_id, current_user)
    self.excursions.select{|p| p.id==excursion_id}.first.users.delete(current_user)
end

Of course the first option is much much better :)

manosagent
  • 614
  • 8
  • 18
0

excursion_instance.users.find(<user_id>).destroy should do the job. In this kind of relationships destroy means, destroy the record in the join table that associates the two entities, in this case, the table ExcursionsUsers. Give it a try.

ichigolas
  • 7,595
  • 27
  • 50
  • are you sure that your code is deleting the relationship and not the user itself? – Rafa Paez Feb 23 '14 at 18:45
  • Yeap, that happens when the relationship is a `through` one, i.e. your excursions have many users through ExcursionsUsers. Give it a try on the console and see what happens. – ichigolas Feb 23 '14 at 18:47
  • `.find().destroy` will find and load the user and will destroy the user not the relationship. – Rafa Paez Feb 23 '14 at 18:50
  • I'm trying it in a rails app and it works. Anyway, try with `project.excursions.find(excursion_id).users.delete(user_id)` – ichigolas Feb 23 '14 at 18:54
0

The following should work

def remove_user_from_excursion(excursion_id, current_user)
  excursions.find(excursion_id).users.destroy(current_user)
end
Rafa Paez
  • 4,820
  • 18
  • 35