mysql - Rails 如何迭代 has_one 呢?

标签 mysql ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

这是场景:

所以,产品与反馈没有任何关系,但订单有 我想将反馈显示为属于产品

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/

相关文章:

php/mysql 可能返回不在数据库中的数据吗?

ruby-on-rails - 将电子邮件存储为小写有什么问题吗?

ruby-on-rails - Rails 项目不断崩溃。最新错误: missing :controller key

python : error when insert mysql database

mysql - 第 1 行第 'column name' 列的数据被截断

php - Laravel 在 MySQL 中的 JSON 字段的帮助下创建 API 返回

mysql - Rails 测试数据库缺少主键

mysql - 在运行时连接到 ruby​​ 中的两个不同数据库

ruby - 将 .capitalize 应用于 ruby​​ 中的西里尔字母数组

Ruby:Random#rand 和 Kernel#rand 之间的区别