SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Mar 2006
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    RoR newbie, agile web dev book question

    I am a ruby newby and I am reading through pragmatic's agile web dev book. Anyway there is a part in the "build a store" code that I don't understand.

    In controllers/store_controller.rb:
    Code:
     def add_to_cart
        product = Product.find(params[:id])
        @cart = find_cart   #sets cart as session 
        @cart.add_product(product) #.add_product is in models/cart.rb
        redirect_to(:action => 'display_cart')    
        rescue 
        logger.error("Attempt to access invalid product #{params[:id]}") 
        redirect_to_index('Invalid product') 
        
      end
    the line: @cart.add_product(product) I don't understand why Rails knows to look for the "cart.rb" file in models for that particular method. Does it just scan all of the controller, then move through each model to look for that method? Or something else?

    thanks.

  2. #2
    SitePoint Evangelist
    Join Date
    Feb 2006
    Location
    Worcs. UK
    Posts
    404
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think the bit of code you need to consider is that of the find_cart method in the third line you quote. I'm not sure at which stage of the book you are at, but the final version looks like this:
    Code:
    def find_cart
      @cart = (session[:cart] ||= Cart.new)
    end
    That code basically says, if a Cart object isn't already being held in the session data, create a new Cart object. So @cart is created as a Cart object here.

    Rails will look for the object definition within the models. cart.rb starts with the class statement:
    Code:
    class Cart
    As an object of class Cart, Rails assigns methods and properties to @cart object based on the code within the class statement in cart.rb. One of those is the add_product method.

  3. #3
    SitePoint Member
    Join Date
    Mar 2006
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ahh, there it is. Yes I did go through that part but the Cart.new slipped past me. That's what I get for reading this stuff at 4 in the morning. Thanks ReggieB.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •