I have 3 model
class User < ActiveRecord::Base
has_many :profiles
has_many :companies, :through => :profiles
end
class Company < ActiveRecord::Base
has_many :profiles
has_many :users, :through => :profiles
end
class Profile < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
when I want to query all companies form user. I just type
u = User.find(:first)
companies = u.companies
But when I want to query only companies that have
profile.is_publish == ture
What is the right way I should do
First: I should create method in User to do that
def published_companies
companies.where('profiles.is_publish' => true)
end
companies = u.published_companies
Second: I should create scope in Company
scope :published, joins(:profiles).where('profiles.is_publish' => true)
companies = u.companies.published
Third: I should create a scope in Profile
companies = u.profile.published.companies
the first way is easy one and the third is cool but I don’t know How to do it.
Create the scope on
Companylike:Then on user you call:
To check the validness of the code you can use
to_sqlmethod.