这是场景:
所以,产品与反馈没有任何关系,但订单有 我想将反馈显示为属于产品
model FEEDBACK
has_one :order
has_one :product, through: :order
model ORDER
belongs_to :product, touch: true
belongs_to :feedback
model PRODUCT
has_many :feedbacks
has_many :orders
我想循环获取产品的反馈
例如
controller HOME
@total_feedbacks = Feedback.joins(:product).where('products.id = ?', @product.id).where('buyer_feedback_date is not null').count
@average_rating_from_buyers = Feedback.joins(:product).where('products.id = ?', @product.id).where('buyer_feedback_date is not null').rated(Feedback::FROM_BUYERS).average(:buyer_rating)
view HOME
<table id="posts" class="product_table">
<tbody class="page">
<tr>
<% @products.last(22).each do |product|%>
<td>
<%=link_to product_path(product.id), :class=>"product" do %>
<span class="productName">
<%=product.name %></span>
<span class="price"><%=number_to_currency(product.price, :unit=> "R$") %></span>
<% if product.vitrine.feedbacks.present? %>
<div class="productFeeback">
<div><%= @average_rating_from_buyers %>"></div>
<%=@total_feedbacks %>
</div>
<% end %>
<% end %>
</td>
<% end %>
</tr>
</tbody>
</table>
用这个代码我得到
undefined method `id' for nil:NilClass
有人有空余的提示吗?谢谢
最佳答案
在您的产品型号上,尝试:
has_many:反馈,通过::订单
对于“未定义的方法 id”错误,如果您可以包含更多的堆栈跟踪,将会有所帮助。
仅根据示例代码,我认为它必须在 Controller 中发生。 @product.id 正在被引用,但我没有看到 @product 被设置。
关于mysql - Rails 如何迭代 has_one 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42963474/