Rails - 将模型中的值导入应用程序布局

时间:2012-06-21 15:03:47

标签: ruby-on-rails view model

我想从模型中获取'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>

编辑:

我已尝试将以下内容放入应用程序助手中,但它无法正常工作。它要么提出一个未定义的方法/变量错误信息,要么说“你的购物车中有0件物品”,即使那里有物品。我已经尝试将@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

我哪里错了?

3 个答案:

答案 0 :(得分:1)

Nils指出你必须指定@total_current_items(在你的控制器中),以便你可以访问它。现在查看您的视图代码,我猜您会在@cart中找到相关信息。

成员变量@cart(成员变量因为它有@)在控制器中分配。您也可以在视图中访问控制器中分配的成员变量。

您想了解购物车附加了多少line_items。您已经在检查购物车中是否有任何line_items(否则您将无法显示您想要实现的内容)。所以不要检查你的数组是否为空。尝试获取数组的长度,即购物车中当前存在的line_items数。

答案 1 :(得分:1)

这是一个部分答案,但评论不能真正有代码块:

您应该将代码设置为@codetotal_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

答案 2 :(得分:0)

您需要在控制器中指定total_current_items才能在您的视图中使用。

cart也是如此,如果没有设置它。