用户和个人资料之间的关联关系

问题描述 投票:0回答:2

我正在考虑创建模型UserRole。用户可以创建他们想要的许多角色。创建角色后,用户可以从列表中选择一个角色并分配给自己。因此,每个角色可以有许多用户,并且一个用户属于一个角色。但这似乎有点不可思议,因为角色应该首先存在。我不确定这是否是在用户和角色之间建立关系的正确方法,因为我希望用户可以编辑角色并应用于所有用户。

假设用户为has_one角色,而个人资料为belong_to,则该用户要更新角色,则需要一个一个地编辑所有用户,这很浪费时间。这就是为什么我认为用户可以创建任意数量的角色,然后他们可以从列表中选择一个角色并分配给用户本身。

这里是视图:

<%= form_for(@user, remote: true) do |f| %>

<%= f.text_field :email, class: "form-control", autofocus: true, autocomplete: "off" %>
<%= f.check_box :admin, class:"checkbox" %>
<%= f.check_box :owner, class:"checkbox" %>

<%= f.fields_for :user_role do |ff| %>
<%= ff.collection_select :role_id, @roles, :id, :role_name, include_blank: false %>
<% end %>             

<%= f.button "Create",  class: "btn btn-success" %>

<% end %>

我不确定我的想法是否是正确的做法,请告知。谢谢。

ruby-on-rails activerecord associations
2个回答
0
投票

这可以是has_one:through关系。

class User < ApplicationRecord
  has_one :user_role
  has_one :role, through: :user_role
end
class Role < ApplicationRecord
  has_one :user_role
  has_one :user, through: :user_role
end
class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

这里,User将能够创建他想要的任意多个角色。那么您可以将User链接到他在联接表中选择的Role


0
投票

嗯,我认为用户和角色之间存在一对一的关系。用户可以创建许多角色,但只能为其分配一个角色。如果您想知道“谁创建了该角色?”,角色也可以属于用户。 (您需要使用类似has_one :role_creator, class_name: "User", foreign_key: "role_creator_id"的内容)

© www.soinside.com 2019 - 2024. All rights reserved.