views:

94

answers:

1

Hey,

I have two models Users and Roles. I have setup a many to many relationship between the two models and I have a joint table called roles_users.

I have a form on a page with a list of roles which the user checks a checkbox and it posts to the controller which then updates the roles_users table.

At the moment in my update method I am doing this because I am not sure of a better way:

role_ids = params[:role_ids]
user.roles.clear
role_ids.each do |role|
  user.roles << Role.find(role)
end unless role_ids.nil?

So I am clearing all the entries out then looping threw all the role ids sent from the form via post, I also noticed that if all the checkboxes are checked and the form posted it keeps adding duplicate records, could anyone give some advice on a more efficent way of doing this?

A: 

You can do a direct assignment, as that handles the dirty work for you:

user.roles = params[:role_ids].present? ? [ ] : Role.find_all_by_id(params[:role_ids])

ActiveRecord should take care of creating new associations or removing those that are no longer listed. If anything precludes your join model from saving, such as a failed validation, you may have issues, but in most situations this should work as expected.

I hope you're using a has_many ..., :through for this one and not the deprecated has_and_belongs_to_many that keeps haunting so many Rails apps because of old example code.

tadman
Cheers for that, works perfectly, I was infact using the has_and_belongs to many but read about the :through approach and moved it to that. Thanks again.
Eef