尝试在我的杂货店应用中显示单个项目。
使用item.product.title& item.quantity。
因为我想做订单的小计。目前我
NoMethodError in Orders#show - undefined method `product' for #<OrderItem:0x007fe53514d6e8>
orders.show.html
<h1>Your Order</h1>
<table class="table table-striped">
<tr>
<th>Customer</th>
<td><%= @order.user_id %></td>
</tr>
<tr>
<th>Status:</th>
<td><%= @order.status %></td>
</tr>
<tr>
<th>Items:</th>
<td><%= @order.order_items.count %></td>
</tr>
<tr>
<th>Items</th>
<th>Title</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Subtotal</th>
</tr>
<% @order.order_items.each do |item| %>
<tr>
<td></td>
<td><%= item.product.title %></td> <-----Error
<td><%= item.quantity %></td>
<td><%= item.product.price %></td>
<td><%= print_price item.subtotal %></td>
<% end %>
</table>
<%= link_to 'Edit', edit_order_path(@order) %> |
<%= link_to 'Back', orders_path %>
product.rb
class Product < ActiveRecord::Base
validates_numericality_of :price
validates :stock ,numericality: { greater_than_or_equal_to: 0 }
has_many :order_items
end
order.item
class OrderItem < ActiveRecord::Base
belongs_to :Order
belongs_to :Product
validates :order_id, :product_id, presence: true
end
完整错误
NameError in Orders#show
undefined local variable or method `product' for #<#<Class:0x007fe539003568>:0x007fe5391abd48>
app/views/orders/show.html.erb:30:in `block in _app_views_orders_show_html_erb__2160818799905733439_70311241143160'
app/views/orders/show.html.erb:27:in `_app_views_orders_show_html_erb__2160818799905733439_70311241143160'
答案 0 :(得分:2)
订单商品需要
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order_id, :product_id, presence: true
end
最容易想到的方法是,belongs_to定义了返回与连接关联的对象的方法。所以:产品 - 创建order_item.product。不是:产品