Reputation: 2444
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
My problem is how do i update the values of user roles on the 3rd table.
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;
Upvotes: 0
Views: 709
Reputation: 2444
I have found a way to doing the updates on the third relationship table as following code,
Here is the code I have written
@user = User.find(user_params[:id])
@roles = @user.roles.all
@roles = @user.roles.all
for role in @roles
if role
@user.roles.delete(role)
end
end
@user = User.find(user_params[:id])
@roles = user_params[:roles];
for role in @roles
@user.roles << Role.find(role)
end
if @roles
@user.save
end
Upvotes: 0
Reputation: 310
If you set up a many_to_many connection through rails, like below for example, then you don't have to touch the relational table. As nifCody said, you simply have to tell rails that you're appending to the user's roles and (as long as you have the proper associations) rails will automatically update the middle table for you.
class User < ApplicationRecord
has_many :user_roles
has_many :roles, through: :user_roles
end
class UserRole < ApplicationRecord
belongs_to :user
belongs_to :role
end
class Role < ApplicationRecord
has_many :user_roles
has_many :users, through: :user_roles
end
But essentially, whatever is in the table is what rails sees. So if you already have data in the tables, you can leave it and continue with the method nifCody suggested. It is simply a different way of modifying the data not accessing it.
Upvotes: 0
Reputation: 470
You should be able to do something like that:
role = Role.find(ID)
user.roles << role
user.save
Upvotes: 1