1

「レールを使用したアジャイル Web 開発」という本からデポ アプリを作成する作業を進めています。横の列にカートが表示される代わりに、「(x) 個のアイテムが現在カートに入っています」というステートメントが表示されるように、その機能を変更したいと考えています。

私はこのコードを持っています:

line_items コントローラー (カートに入っているアイテム):

def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to store_url }
    format.js { @current_item = @line_item }
    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

そしてカートコントローラー:

def show
begin
  @cart = Cart.find(params[:id])
rescue ActiveRecord::RecordNotFound
  logger.error "Attempt to access invalid cart #{params[:id]}"
  redirect_to store_url, notice: 'Invalid cart'
else
  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @cart }
  end
 end
end

「(x) 個のアイテム」をカート内の現在のアイテム数に変更できるように、アプリケーション レイアウト ビューからカートを参照するにはどうすればよいですか? 私は試してみましたが@total_cart.line_items、私が考えることができる他のすべてのバリエーション。

編集:カートモデルにコードがありますcurrent_item.quantity-これが必要な値であるため、アプリケーションレイアウトビューでこれをどのように参照しますか? ありがとう!

4

1 に答える 1

0

カート内のアイテム数を合計する item_count というメソッドをカートに追加します。

def item_count
  line_items.inject{|sum, line_item| sum + line_items.quantity
end

次に、アプリケーションのレイアウト ビューで、@cart.item_count を参照するだけです。

于 2012-09-03T18:43:29.177 に答える