I'm facing an issue on the many to many relationship table using ruby on rails.
I have two tables and a relationship table(which is a joining table). They are named as follow
- User
- Role
- Role_User
My problem is how do i update the values of user roles on the 3rd table.
Example
If I assign a
user_id 34 to admin(role_id = 2)
user_id 34 to supervisor(role_id = 3)
I should have two entries on Role_User table. Now I would like to update user_id 34 to admin(role_id = 1) How do I do this on rails
I have updating the user details with update_all
command on rails like below
@user = User.where(id: user_params[:id]);
@user.update_all(
first_name: user_params[:first_name],
last_name: user_params[:last_name],
email: user_params[:email],
contact_number: user_params[:contact_number],
user_name: user_params[:user_name],
password: user_params[:password]
);
I try to update the role of users using the following code but it fails
@roles = user_params[:roles];
for role in @roles
@user.roles << Role.find(role)
end
@user.save;