0
試圖在我的雜貨應用程序上顯示個別項目。Rails 4:無法顯示個別訂單
使用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'
你可以發佈完整的錯誤還張貼你的顯示操作 – Mandeep
張貼的錯誤代碼和更新的代碼 – Neil
你沒有按照Rails的命名約定,例如'belongs_to:product'做任何好處。錯誤信息是正確的,你沒有'product'方法。 –