0
votes

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

  1. User
  2. Role
  3. 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;
3

3 Answers

1
votes

You should be able to do something like that:

role = Role.find(ID)
user.roles << role
user.save
0
votes

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.

0
votes

I have found a way to doing the updates on the third relationship table as following code,

  1. First I delete all role_id for the particular user_id
  2. Then insert the roles as new to the particular user_id

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