views:

48

answers:

2

I am working on the depot tutorial in Agile RoR. I have looked at this for a while and don't see an error. What am I missing? I get the following error when I add an item to a cart

I have run the migration.

.. /Users/computername/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:376:in method_missing' /Users/computername/Documents/rails_projects/depot/app/models/cart.rb:5:in add_product' /Users/computername/Documents/rails_projects/depot/app/controllers/line_items_controller.rb:46:in `create'

Here is my create method

  def create 
    @cart = find_or_create_cart 
    product = Product.find(params[:product_id]) 
    #@line_item = @cart.line_items.build(:product => product)
    @line_item = @cart.add_product(product.id)
..

my cart model

class Cart < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy

  def add_product(product_id) 
    current_item = line_items.where(:product_id => product_id).first 
    if current_item
      current_item.quantity += 1
    else
      current_item = LineItem.new(:product_id=>product_id)
      line_items << current_item
    end
    current_item
  end
end
+2  A: 

use conditions instead of where

line_items.conditions(:product_id => product_id).first 
Salil
Is it find with conditions that I would want?Like? current_item = line_items.find(:first,:conditions =>{:product_id => product_id})That appears to work.
Maestro1024
`current_item = line_items.first(:conditions =>{:product_id => product_id})` is slightly more concise. Have you seen the [Guide](http://guides.rubyonrails.org/active_record_querying.html#conditions)?
Bryan Ash
I am sure you are correct. No I have not seen the guide. I looked at the api reference and saw sort of how find and conditions work.So, I guess when I move this code to Rails 3 I have to change this line?
Maestro1024
A: 

where is introduce with ActiveRecord 3. So it's normal it failed in your case, because you use ActiveRecord 2.3.x

shingara