James Benz
James Benz

Reputation: 13

How do I remove a user association without destroying their records?

I am having difficulty with my associations and have been digging around trying to find an answer relevant to my problem. I have a selection box in my form that adds users to a study when it is created. The problem is that if I edit the list and remove a user from a study and then add them back it deletes their answers. I am still learning RoR and have been given the task of getting some existing code to function this way. The study model has many users through answers, so how do I edit the study users without deleting the answers? my form:

= select_tag("users[]", options_for_select(@users.collect { |ff| [ff.full_name, ff.id] }, @study.users.collect { |fs| fs.id }), | {:multiple=>true, :id => "users"})                                                                                      |

my study.rb:

has_many :users, :through => :answers
has_many :answers, :group => :grouping_number
accepts_nested_attributes_for :answers 

my user.rb

has_many :answers
has_many :studies, :through => :answers

my answer.rb

belongs_to :user
belongs_to :study
belongs_to :question

I realize that this may be something simple that I have overlooked, which is often the case when spending too long looking at something, but any point in the right direction would be much appreciated.

Upvotes: 1

Views: 181

Answers (2)

thorsten müller
thorsten müller

Reputation: 5651

Does it make sense, that a User can belong to a study only if he gives answers? I would somehow assume an independent relation UserStudies. In your case as a separate model, not just a has_and_belongs_to_many relationship. This would allow you to have a flag "active" in this model and that way activate or deactivate the relation. Then you just add a condition to your belongs_to association.

That's roughly what gems like those Deefour already recommended would do.

Upvotes: 1

deefour
deefour

Reputation: 35360

You might benefit from using a Soft Delete gem like acts_as_paranoid.

This way the associations will remain intact but be flagged as deleted instead of actually being removed from the database. The benefit of this is you can still query active record for user's answers even after their study association is 'deleted', while the behavior of the association actually having been deleted from the application will remain the same.

Upvotes: 2

Related Questions