【发布时间】:2016-03-30 19:06:26
【问题描述】:
您好,我在为我在网站中构建的购物车创建此条件时遇到了一些麻烦,以便在零件销售时显示总数。在我的模式中,我有零件,line_items,它的 id 是零件和购物车,以及购物车。零件具有折扣属性。如果部件有折扣,它将显示折扣和部件的新价格。我的 line_items 有一个名为 line_item_discount 的方法,如果一个部分包含折扣,它将创建一个新的部分总和。尽管它显示了零件、折扣和新价格,但购物车总数并未更新。
我在这里创建了一个名为 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 部分里面了我已经尝试了很多方法来创建条件,但我不断收到这样的消息
由于某种原因,购物车没有出现 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?' } %>
感谢您对此的任何帮助和建议
【问题讨论】:
标签: ruby-on-rails activerecord undefined