Rails 用户和配置文件之间的关联

Rails association between User and Profile

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

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

视图如下:

<%= 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 %>

我不确定我的想法是否正确,请指教。谢谢。

嗯,我认为 User 和 Role 是 1 对 N 的关系。用户可以创建多个角色,但只能将其中一个角色分配给自己。如果你想知道"Who created that role?",角色也可以属于一个用户。 (你需要使用类似 has_one :role_creator, class_name: "User", foreign_key: "role_creator_id" 的东西)

这可以是 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可以创造任意多的角色。那么你可以linkUser到他在table.

中选择的Role