【发布时间】:2019-02-05 23:27:04
【问题描述】:
我需要将用户组存储在其他组中,有点像 Windows Active Directory。
我有以下有效的方法
ActiveRecord::Schema.define do
create_table :users do |table|
table.column :name, :string
end
create_table :groups do |table|
table.column :name, :string
end
create_join_table :users, :groups do |t|
end
end
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
# has_and_belongs_to_many :groups
end
peter = User.create(id: 1, Name: 'Peter')
thomas = User.create(id: 2, Name: 'Thomas')
inf = Group.create(id: 1, Name: 'Informatics')
peter.groups << inf
inf.users << thomas
p User.find_by(Name: 'Peter').groups
p Group.find_by(Name: 'Informatics').users
但我也想做以下事情
sm = Group.create(id: 2, Name: 'System')
inf.groups << sm
最简单的方法是什么?
【问题讨论】:
-
你有什么理由使用 has_and_belongs_to 而不是 has_many => 吗?后者可能更灵活一些。
-
@BKSpureon 组可以有很多用户和组,用户可以有很多组,这可能与 has_many_through 吗?为什么更灵活?你有例子吗?
-
您无需(实际上任何)相应成本即可保持灵活性。如果您想在连接表/连接模型中添加额外的字段怎么办?如果您希望将来在您的连接模型中包含回调和验证逻辑怎么办?您可以免费保留额外的灵活性。
-
@peter 这里是讨论此问题的文档的链接:guides.rubyonrails.org/…
标签: ruby activerecord orm relational-database self-referencing-table