22 Apr 2009, 11:07
Generic-user-small

Steven Noble (21 posts)

In “8.2 Iteration C1: Creating a Cart”, we place the following code in cart.rb:

def add_product(product) @items << product end

Somewhere along the line, I go the impression that only class methods went in models, but this looks like an object method to me. What am I missing?

22 Apr 2009, 20:49
Samr_small_pragsmall

Sam Ruby (584 posts)

Models can, and often do, have object methods!

23 Apr 2009, 07:59
Generic-user-small

Steven Noble (21 posts)

Thanks Sam.

Looking through the code we’ve built so far, I see a fair degree of flexibility in where we define and call methods:

A public class method (self.find_products_for_sale) defined in one model (product.rb) and called in another model altogether (store_controller.rb)

# A public class method (initialize/Cart.new) defined in one model (cart.rb) and called in a controller with an unrelated name (store_controller.rb) # A public instance method (increment quantity) defined in one model (cart_items.rb) and called in another model altogether (cart.rb) # A public instance method (add_product) defined in one model (cart.rb) and called in controller with an unrelated name (store_controller.rb) # A public instance method (add_to_cart) defined in a controller (store_controller.rb) and called in a view with a related path (store/index.html.erb) # A protected instance method (price_must_be_at_least_a_cent) defined in a model (product.rb) and called in the same model

I’m looking for patterns here. So far I’m seeing:

To make a public method available to a view, define it in the controller with the related name

# To make a public method available in any model or controller, define it in any model # To make a private method available to a model, define it in that model # No difference between class and instance methods

Correct? Why? Is your answer affected by the fact that, at this stage in the book, we’ve not yet touched on associations or routing?

If it’s relevant to your answer, why are there not carts and cart_items controllers when we have a carts and cart_items models?

Many thanks in advance,

Steven.

11 Jul 2010, 20:18
Generic-user-small

John Winston Brown (1 post)

I know this post is really old, but I have been quite confused about this, as well. Steven (if you’re still hanging around the forums), I found your post articulate and helpful. Sam, are his observations correct?

By the way, Sam, great book. I’ve been doing fairly well, until Iteration C, where some of the stuff we’ve done is looking a bit like black magic to me, and I’m getting lost.

  You must be logged in to comment