繁体   English   中英

更新多对多关系表上的值

[英]Updating the values on Many-to-Many relationship table

我在使用Rails的ruby的多对多关系表上面临一个问题。

我有两个表和一个关系表(这是一个联接表)。 他们被命名如下

  1. 用户
  2. 角色
  3. 角色用户

我的问题是如何更新第三张表上的用户角色的值。

如果我分配一个

user_id 34至admin(role_id = 2)

超级用户的user_id 34(role_id = 3)

我应该在Role_User表上有两个条目。 现在我想将user_id 34更新为admin(role_id = 1)我如何在rails上执行此操作

我已经在如下所示的轨道上使用update_all命令更新了用户详细信息

@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]
);

我尝试使用以下代码更新用户的角色,但失败

@roles = user_params[:roles];
for role in @roles
  @user.roles << Role.find(role)
end

@user.save;

您应该能够执行以下操作:

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

如果您通过导轨建立了many_to_many连接,例如以下所示,则不必触摸关系表。 正如nifCody所说,您只需要告诉rails您将追加到用户角色,并且(只要您具有正确的关联)rails就会自动为您更新中间表。

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

但本质上,表中的任何内容都是Rails看到的。 因此,如果表中已经有数据,则可以将其保留并继续使用nifCody建议的方法。 这只是修改数据而不访问数据的另一种方式。

我找到了一种在第三种关系表上进行更新的方法,如下所示,

  1. 首先,我删除特定user_id的所有role_id
  2. 然后将角色作为新角色插入到特定的user_id中

这是我写的代码

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM