购物车模型基本逻辑Ruby on Rails中的数量

时间:2012-11-03 15:18:13

标签: ruby-on-rails ruby-on-rails-3 if-statement model logic

我正在尝试将一些非常基本的逻辑应用到我的视图中,但到目前为止还没有失败。

如果存在以下情况,我想要的是返回item.discount_price:

  1. item.product_id等于1
  2. Cart.item.quantity计数等于或高于2.
  3. 目前我有以下内容:

    项目模型

    class Item < ActiveRecord::Base
    belongs_to :product
    belongs_to :cart
    
    def price_check
    
        if  Item.product_id = 1 && Item.quantity.count >= 2 
            return Item.discount_price
        else
            return Item.unit_price
        end 
    
    end
    

    查看

    <% for item in @cart.items %>
    <tr class="<%= cycle :odd, :even %>">
      ...
      <td class="price"><%= gbp(item.price_check) %></td>
      ...
    </tr>
    
      

    协会如下:

    Cart - has_many :items
    Items - Belongs_to :cart and :products
    Products - has_ many :items
    

    我一直收到的错误:

     NoMethodError in Carts#show
    
    Showing C:/Sites/checkout/app/views/carts/show.html.erb where line #12 raised:
    
    undefined method `quantity' for #<Class:0x50c3058>
    
    Extracted source (around line #12):
    
    9:        <tr class="<%= cycle :odd, :even %>">
    10:       <td><%=h item.product.name %></td>
    11:       <td class="qty"><%= item.quantity %></td>
    12:       <td class="price"><%= gbp(item.price_check) %></td>
    13:       <td class="price"><%= gbp(item.full_price) %></td>
    14:       <td><%= button_to 'Remove', item, :method => :delete %></td>
    15:       </tr>
    
    app/models/item.rb:12:in `price_check'
    app/views/carts/show.html.erb:12:in `block in _app_views_carts_show_html_erb___389237738_48997308'
    app/views/carts/show.html.erb:8:in `_app_views_carts_show_html_erb___389237738_48997308'
    

    人们可以提供任何帮助来解决这个问题,我将不胜感激!谢谢你

2 个答案:

答案 0 :(得分:1)

RadBrad有正确的想法,但错误的实施

def price_check
  # Product Discount for Lavender Heart (Product code 001, greater than 2 in cart)        
  # Thought: Shouldn't you check to see if the name of the item is "Lavender Heart"?
  #          Checking if the product_id is 1 makes this test brittle
  if product_id == 1 && cart.items.quantity.count >= 2 
    discount_price
  else
    unit_price
  end 
end

答案 1 :(得分:-1)

第一个明显的问题是:

if  Item.product_id = 1 && Item.quantity.count >= 2 

您要求调用CLASS方法product_id。你想要实例方法,即

if @item.product_id == 1 && @item.quantity >= 2

通常情况下会出现以下情况:

@item = Item.find(params[:id])