Re: Syntax for calling the has_many class methods

Jason Roelofs
Wed, 11 Oct 2006 14:45:11 -0000

#line_items is an instance methods. You can''t call them on a Class
because
there is no link between the models. Try to think of it through the
resulting SQL queries.

self.line_items -- find all line_items with a order_id of self.id

You have to think of what ''Order.line_items << li''
means. You can''t do
Order.line_items because that would be like saying "find all line_items
with
order_id of Class.id" which is obviously wrong. Line_items are linked to
Orders and so you need to have an order to find line_items.

Just keep in mind that all method calls on ActiveRecord objects are in fact
queries to the database (or cached queries).

Hope that helped.

Jason

On 10/11/06, Jeff <objectis-/E1597aS9LQAvxtiuMwx3w@public.gmane.org>
wrote:
>
>
> I have a simple Active Record model:
>
> class Order < ActiveRecord::Base
>   has_many  :line_items
>   def add_line_items_from_cart(cart)
>     cart.items.each do |item|
>       li = LineItem.from_cart_item(item)
>       line_items << li
>     end
>   end
> end
>
> This syntax works fine:
> line_items << li
>
> This also works:
> self.line_items << li
>
> But this syntax fails with an error (undefined method `line_items''
for
> Order:Class):
> Order.line_items << li
>
> Why the error?
>
> Thanks,
> Jeff
>
>
> >