1

ビューで使用するために、モデルから「current_item.quantity」を取得したいと考えています。つまり、アプリケーション レイアウト ビューで「(x) 個のアイテムを現在カートに入れる」ことができるようにしたいと考えています。どうすればこれを行うことができますか?私が考えることができる「@total_current_items」などのすべての組み合わせを試しました。ありがとう!!

役立つ場合のモデルコードは次のとおりです。

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)
    current_item.price = current_item.product.price
  end
  current_item
end

def total_price
  line_items.to_a.sum { |item| item.total_price }
end

def decrease(line_item_id)
  current_item = line_items.find(line_item_id)
  if current_item.quantity > 1
    current_item.quantity -= 1
  else
    current_item.destroy
  end
  current_item
end

def increase(line_item_id)
  current_item = line_items.find(line_item_id)
  current_item.quantity += 1
  current_item
end
end

リクエストに応じて、ビュー コード (関連部分) を次に示します。

<% if @cart %>
<%= hidden_div_if(@cart.line_items.empty?, id:'cart') do %>
<div class="row-fluid">
        <a class="btn btn-success menu" id="menubutton" href="<%= cart_path(session[:cart_id]) %>">View Cart</a>
                </div>
                <div class="row-fluid"> 
                You have <%= pluralize(@total_current_items, "item") %>in your cart.    
                </div>

                <% end %>           
            <% end %>
</div>

編集:

アプリケーションヘルパーに以下を入れてみましたが、うまくいきません。未定義のメソッド/変数のエラー メッセージが表示されるか、カートに商品が入っていても「カートに商品がありません」と表示されます。@total_items、total_items などを入れてビューで参照しようとしましたが、Rails は初めてで、どうすれば動作するのかわかりません!

 def total_items
   @line_items = LineItem.find(params[:id])
   @total_items = @line_items.to_a.sum { |item| item.total_quantity}
 end

どこが間違っていますか?

4

3 に答える 3

1

これは部分的な答えですが、コメントに実際にコードブロックを含めることはできません。

@codeおよびtotal_current_itemsApplicationController保護されたメソッドとして割り当てるコードを配置する必要があります。次に、それをbefore_filterとして使用して、メソッドがすべてのコントローラー(ページ)の前に実行されるようにします。

class ApplicationController < ActionController::Base
  before_filter :get_cart    

  protected
  def get_cart
    @cart = SOMETHING
    @total_current_items = SOMETHING
  end
end

before_filter- http: //guides.rubyonrails.org/action_controller_overview.html#filters

于 2012-06-22T11:33:54.443 に答える
1

Nilsが指摘したように、@total_current_itemsアクセスできるように(コントローラーで)割り当てる必要があります。ビューコードを見ると、 に情報が含まれていると思います@cart

メンバー変数@cart(メンバー変数には があるため@) がコントローラーに割り当てられます。ビューでも、コントローラーに割り当てられたメンバー変数にアクセスできます。

カートに添付されている line_items の数を調べたいとします。カートに line_items があるかどうかをすでに確認しています(そうでない場合、達成したいものは表示されません)。したがって、配列が空かどうかをチェックする代わりに。配列の長さ、つまり現在カートにある line_items の数を取得してみてください。

于 2012-06-22T05:50:53.470 に答える
0

ビューで使用できるようにするには、コントローラーで割り当てる必要がありtotal_current_itemsます。

それがcart設定されていない場合も同様です。

于 2012-06-21T16:58:39.033 に答える