small medium large xlarge

14 Jun 2009, 19:55
Stephen Smithstone (6 posts)

in the code for add_line_items_from_cart(cart)

it uses

line_items « li

where line_items is defined as a

has_many :line_items

which is a an instance variable

so in the code should it not be

@line_items « li

as i thought

line_items would be declared as a local variable

25 Jun 2009, 11:39
David Spindle (9 posts)

Now that is interesting. I am new to ruby myself and am curious as to what the answer is. Like you, I thought that instance variables are always prefixed by “@”. I would think that with @line_items it would also work.

Is it perhaps calling a reader method named :line_items that was auto-generated from has_many? This would be consistent with what attr_reader does I think. Of course I could be totally wrong here… its all new to me!

26 Jun 2009, 03:15
David Spindle (9 posts)

Well I played around with this and I think I know what is going on now. The reason that the code is calling @line_items « li@ is because it is invoking the @collection«(object, …)@ method added by @has_many@. See the @has_many@ docs for more details.

If you used @@line_items « li@ instead, this would fail since the @@line_items@ reference is nil and I doubt nil implements a @«@ method. I am pretty sure these collection methods added by @has_many@ will initialize the instance variable because if you invoke the accessor first, you can use the instance reference.

@line_items << li
26 Jun 2009, 09:46
Stephen Smithstone (6 posts)

Yeh i managed to get that section and found the part about the has_many adding metods to the objects , as im new to dynamic languages this was a newbie mistake from me

You must be logged in to comment