在我的项目中,我使用Relationship 类(在我命名为ActsAsRelatingTo 的gem 中)作为连接模型。它看起来像这样:
# == Schema Information
#
# Table name: acts_as_relating_to_relationships
#
# id :integer not null, primary key
# owner_id :integer
# owner_type :string
# in_relation_to_id :integer
# in_relation_to_type :string
# created_at :datetime not null
# updated_at :datetime not null
#
module ActsAsRelatingTo
class Relationship < ActiveRecord::Base
validates :owner_id, presence: true
validates :owner_type, presence: true
validates :in_relation_to_id, presence: true
validates :in_relation_to_type, presence: true
belongs_to :owner, polymorphic: true
belongs_to :in_relation_to, polymorphic: true
end
end
所以,在你的 User 模型中,你会说:
class User < ActiveRecord::Base
has_many :owned_relationships,
as: :owner,
class_name: "ActsAsRelatingTo::Relationship",
dependent: :destroy
has_many :organizations_i_relate_to,
through: :owned_relationships,
source: :in_relation_to,
source_type: "Organization"
...
end
我相信您可以不使用 source_type 参数,因为可以从 :organizations 推断出加入的类 (Organization)。通常,我加入的模型无法从关系名称中推断出类名,在这种情况下,我会包含 source_type 参数。
有了这个,你可以说user.organizations_i_relate_to。您可以对任何一组类之间的关系进行相同的设置。
你也可以在Organization 课堂上说:
class Organization < ActiveRecord::Base
has_many :referencing_relationships,
as: :in_relation_to,
class_name: "ActsAsRelatingTo::Relationship",
dependent: :destroy
has_many :users_that_relate_to_me,
through: :referencing_relationships,
source: :owner,
source_type: "User"
所以你可以说organization.users_that_relate_to_me。
我厌倦了必须进行所有设置,因此在我的 gem 中我创建了一个 acts_as_relating_to 方法,以便我可以执行以下操作:
class User < ActiveRecord::Base
acts_as_relating_to :organizations, :teams
...
end
和
class Organization < ActiveRecord::Base
acts_as_relating_to :users, :organizations
...
end
和
class Team < ActiveRecord::Base
acts_as_relating_to :organizations, :users
...
end
所有的多态关联和方法都会“自动”为我设置好。
抱歉,答案很长。希望你能从中找到有用的东西。