Hemant Patil
Hemant Patil

Reputation: 351

Rails has many through with same model

I have one user model and one viewed_contractor model. I am treating user model as customer and contractor. customer can view many contractors by visiting their respective profile.Contractor can be viewed by many customers. I have customer_id and contractor_id in my viewed_contractor. I want to handle this relation as has_many through. Is it possible thorough has_many through?

Upvotes: 1

Views: 691

Answers (1)

hattila91
hattila91

Reputation: 683

It is possible. First, you'd need to specify the class_name option for the belongs_to associations in your ViewedContractor model so that they both refer to your User class. Then you could specify the has_many through: relations in your User model.

Something like this should work:

# 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

Upvotes: 2

Related Questions