Ruby on Rails updating join table records
- by Eef
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?