1

我正在尝试将一些非常基本的逻辑应用于我的观点,但到目前为止还失败了。

如果有以下条件,我想做的是返回 item.discount_price:

  1. item.product_id 等于 1
  2. Cart.item.quantity 计数等于或大于 2。

目前我有以下内容:

物品型号

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'

人们可以提供解决此问题的任何帮助将不胜感激!谢谢 E

4

2 回答 2

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
于 2012-11-03T16:01:49.520 回答
-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])
于 2012-11-03T15:40:31.993 回答