您实际上需要两个不同的关联。第一个是一对多关联。设置它的懒惰方法是:
class Circle < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :circles
end
这通过圈子上的外键列user_id 将用户链接到圈子。但是它非常模棱两可 - user.circles 是什么意思?是用户创建的圈子还是他所属的圈子?即使需要一些配置,也最好更明确一点:
class RenameUserToCreator < ActiveRecord::Migration[6.0]
def change
rename_column :circles, :user_id, :creator_id
end
end
# rails g model circle
class Circle < ApplicationRecord
belongs_to :creator, class_name: 'User'
end
class User < ApplicationRecord
has_many :created_circles,
class_name: 'Circle',
foreign_key: :creator_id
end
接下来,您要向圈子添加成员。这是一个多对多关联,可以使用has_many through: 或has_or_belongs_to_many 完成。两者都使用连接表,但has_or_belongs_to_many 没有模型并且其实际用途非常有限。在命名连接表时,惰性约定是只使用 a 和 b 的组合 - CircleUser,但如果您能想到适合该域的名称,请使用更好的名称。
class Circle
belongs_to :creator, class_name: 'User'
has_many :memberships
has_many :users, through: :memberships
end
# rails g model membership user:belongs_to circle:belongs_to
class Membership
belongs_to :user
belongs_to :circle
end
class User
has_many :created_circles,
class_name: 'Circle',
foreign_key: :creator_id
has_many :memberships
has_many :circles, through: :memberships
end
要记住的一点是,每个关联都必须有一个唯一的名称。如果我们没有经过上一步并写道:
class User
has_many :circles
has_many :memberships
has_many :circles, through: :memberships
end
后一个关联只会破坏前一个关联。