Tuesday, October 4, 2011

[Rails] Active Record Associations - best way to find all items assosciated with a specific company

I have the following associations in my models:

item.rb
belongs_to :manufacturer, :class_name => "Company"
belongs_to :distributor, :class_name => "Company"

company.rb
has_many :items

My question: what is the best way to find all of the items belonging to
a specific company?

If I call Company.items I (understandably) get the error message:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column:
items.company_id: SELECT "items".* FROM "items" WHERE
("items".company_id = ... )

Should I write a little helper method that does what I want, something
along the lines of:

Item.where("items.manufacturer_id LIKE :record OR items.distributor_id
LIKE :record",{:record => @company.id})

or is there a better way to do this through associations?

Would be grateful for any advice.

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate