Rails 多次通过同型号
Rails has many through with same model
我有一个用户模型和一个 viewed_contractor 模型。我将用户模型视为客户和承包商。客户可以通过访问他们各自的 profile.Contractor 来查看许多承包商。我的 viewed_contractor 中有 customer_id 和 contractor_id。我想通过 has_many 处理这种关系。有没有可能彻底has_many通过?
有可能。首先,您需要为 ViewedContractor
模型中的 belongs_to
关联指定 class_name
选项,以便它们都引用您的 User
class。然后您可以在 User
模型中指定 has_many through:
关系。
像这样的东西应该可以工作:
# viewed_contractor.rb
class ViewedContractor < ActiveRecord::Base
belongs_to :contractor, class_name: 'User', foreign_key: :contractor_id
belongs_to :customer, class_name: 'User', foreign_key: :customer_id
end
# user.rb
class User < ActiveRecord::Base
has_many :viewed_contractors_as_contractor, class_name: 'ViewedContractor', foreign_key: :contractor_id
has_many :viewed_contractors_as_customer, class_name: 'ViewedContractor', foreign_key: :customer_id
has_many :visited_contractors, through: :viewed_contractors_as_customer, source: :contractor
has_many :visited_customers, through: :viewed_contractors_as_contractor, source: :customer
end
我有一个用户模型和一个 viewed_contractor 模型。我将用户模型视为客户和承包商。客户可以通过访问他们各自的 profile.Contractor 来查看许多承包商。我的 viewed_contractor 中有 customer_id 和 contractor_id。我想通过 has_many 处理这种关系。有没有可能彻底has_many通过?
有可能。首先,您需要为 ViewedContractor
模型中的 belongs_to
关联指定 class_name
选项,以便它们都引用您的 User
class。然后您可以在 User
模型中指定 has_many through:
关系。
像这样的东西应该可以工作:
# viewed_contractor.rb
class ViewedContractor < ActiveRecord::Base
belongs_to :contractor, class_name: 'User', foreign_key: :contractor_id
belongs_to :customer, class_name: 'User', foreign_key: :customer_id
end
# user.rb
class User < ActiveRecord::Base
has_many :viewed_contractors_as_contractor, class_name: 'ViewedContractor', foreign_key: :contractor_id
has_many :viewed_contractors_as_customer, class_name: 'ViewedContractor', foreign_key: :customer_id
has_many :visited_contractors, through: :viewed_contractors_as_customer, source: :contractor
has_many :visited_customers, through: :viewed_contractors_as_contractor, source: :customer
end