簡體   English   中英

購物車中的數量模型基本邏輯Ruby on Rails

[英]Quantity in Cart Model Basic Logic Ruby on Rails

我正在嘗試將一些非常基本的邏輯應用於我的觀點,但到目前為止卻失敗了。

如果存在以下情況,我想返回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

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

第一個明顯的問題是:

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM