Reputation: 2350
I want to create scope in Company model, so that I can use this line
Company.customer
in order to select all company which has customer type.
The relationship between Company and CompanyType is many-to-many.
Company:
class Company < ActiveRecord::Base
attr_accessible :description, :name, :website, type_ids
has_and_belongs_to_many :types, :class_name => "CompanyType"
#scope :customer, where()
end
CompanyType:
class CompanyType < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :companies
end
For the table in the database, I have table "company_types", "company_types_companies" (connection table between company_types and companies) and "companies"
How do I fill in :customer scope in Company model?
Upvotes: 1
Views: 1706
Reputation: 29599
Try the following
scope :customers, joins(:types).where(company_types: { name: 'customer' })
One thing I would like to raise is I think what you're doing is a bit overkill than simply adding a company_type
column in the companies model. If you're not using CompanyType for anything else, I suggest you add a column instead of using 2 tables.
Upvotes: 2