Ruby on Rails updating join table records

Posted by Eef on Stack Overflow See other posts from Stack Overflow or by Eef
Published on 2010-05-18T10:04:27Z Indexed on 2010/05/18 10:20 UTC
Read the original article Hit count: 245

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails