正直なところ、これまでプログラミングしてきたよりも迷っています。最近、私は5年以上のPHP開発から離れて、Ruby/Railsを試してみようとしています。Railsを使ったアジャイルWeb開発を取り上げ、それをフォローしてきました。私が持っているバージョンが異なるのは、Mac OS X Snow Leopard(元々はMountain Lionに移行したもの)とRuby / Rails 1.8.7/3.2.6です。
カートに数量を追加すると、私のコードは次のように表示されます:cart.rb(モデル)
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(:product_id => product_id)
end
current_item
end
end
line_item.rbモデル内とline_items_controller.rb内にattr_accessible:quantityがあります。@ line_item = current_cart.add_product(product.id)と呼んでいます。初めてカートに商品を追加したときはコードは完全に機能しますが、2回目はRailsでエラーが発生します。
undefined method `+' for nil:NilClass
そして、質問の明白な線を指します(上記のプラス)。助言がありますか?ありがとう。
編集:これがRailsを学ぶための最良のルートであるかどうか、または別の本を手に入れるか、別のWebサイトなどを使用する必要があるかどうかをコメントで推奨できる場合は、コードが間違っているのはこれが初めてではないためです。この本。
編集2:抜粋line_items_controller.rb(40〜56行目)
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_items = @cart.add_product(product.id) #product.id, product didn't work.
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart, :notice => 'Line item was successfully created.' }
format.json { render :json => @line_item, :status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.json { render :json => @line_item.errors, :status => :unprocessable_entity }
end
end
end
また、コードは1つのアイテムに対して機能しますが、同じアイテムの順次追加では機能しないため、.saveとは関係がないと思います。