你好,我已經遇到了一點麻煩,當創建此條件的車我建立在我的網站顯示總當部分有售。在我的模式中,我有零件,包含零件和購物車ID的line_items和購物車。零件具有折扣屬性。如果零件有折扣,它將顯示零件的折扣和新價格。我的line_items有一個名爲line_item_discount的方法,如果一個部分包含折扣,它將創建一個新的部分總和。儘管它顯示零件,折扣和新價格,但購物車總額並未更新。Rails的未定義的局部變量或方法`LINE_ITEM」
我創建了一個名爲total_price_with_discount這裏
class Cart < ActiveRecord::Base
has_many :order_items
belongs_to :user
has_many :line_items, dependent: :destroy
def add_part(part_id)
current_part = line_items.find_by(part_id: part_id)
if current_part
current_part.quantity += 1
else
current_part = line_items.build(part_id: part_id)
end
current_part
end
def total_price
line_items.to_a.sum { |item| item.total_price}
end
def total_price_with_discount
line_items.to_a.sum { |item| item.total_price.line_item_discount}
end
現在我在哪裏卡住是_cart部分裏面我試圖創建一個條件,其中一個零件都有折扣它將使用total_price_with_discount方法,但如果方法零件沒有折扣,它將使用total_price。我已經嘗試了不少方法可以創建條件,但我不斷收到此類郵件
由於某種原因,車沒有line_items或出現部分的實例。
這裏是我的車,部分表,並line_items
create_table "carts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "quantity"
t.decimal "subtotal"
end
create_table "parts", force: :cascade do |t|
t.string "name"
t.text "description"
t.integer "category_id"
t.integer "price"
t.boolean "active"
t.integer "discount"
t.string "image"
t.integer "quantity"
end
create_table "line_items", force: :cascade do |t|
t.integer "part_id"
t.integer "cart_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "quantity", default: 1
end
我的零件模型
class Part < ActiveRecord::Base
has_many :order_items
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
def subtotal
parts.collect { |part| part.valid? ? (part.quantity * part.unit_price) : 0}.sum
end
def apply_discount
price - (discount.to_f/100 * price)
end
end
我line_items模型
class LineItem < ActiveRecord::Base
belongs_to :part
belongs_to :cart
def total_price
part.price * quantity
end
def line_item_discount
part.price - (part.discount.to_f/100 * part.price) * quantity
end
end
,這裏是局部視圖這就是拋錯誤
<h2>Your Cart</h2> <table>
<%= render(cart.line_items) %>
<tr class="total_line">
<td colspan="2">Total</td>
<%unless cart.line_items.part.discount?%>
<td class="total_cell"><%= number_to_currency(cart.total_price) %></td>
<%end%>
<%if cart.line_items.part.discount?%>
<td class="total_cell"><%= number_to_currency(cart.total_price_with_discount) %></td>
<%end%>
</tr>
</table>
<%= button_to 'Empty cart', cart, method: :delete, data: { confirm: 'Are you sure?' } %>
感謝任何幫助和建議與這一個
我用你給我提供了底部的策略,似乎這段代碼實際上是拿實際百分比數字作爲價格而不是折扣價格 – Dan
哦,等等我很抱歉,我忘了將total_price_with_discount從模型中刪除 – Dan
您還必須更改'line_item_discount'中的計算(我已修改了答案中的代碼)。這實際上是在折扣後計算總價,而不是僅僅實現折扣本身。 – MTarantini