【问题标题】:Rails how iterate has_one though?Rails 如何迭代 has_one 呢?
【发布时间】:2017-03-22 22:01:50
【问题描述】:

这是场景:

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

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>

我得到了这个代码

nil:NilClass 的未定义方法 `id'

有人有提示吗?谢谢

【问题讨论】:

  • 欢迎来到 Stack Overflow。 SO 就像一个在线参考网站,语法和拼写都很重要。请在发帖前使用语法检查器和/或拼写检查器。

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


【解决方案1】:

在您的产品模型上,尝试:

has_many :feedbacks, through: :orders

对于“未定义的方法 ID”错误,如果您可以包含更多的堆栈跟踪信息会有所帮助。

仅基于示例代码,我认为它必须在控制器中发生。 @product.id 被引用,但我没有看到 @product 被设置。

【讨论】:

  • 谢谢你,尼克。 @product 正在设置您的意思是在控制器主页上还是在反馈方法中?
  • @product 出现在控制器代码和视图代码中,所以我希望它在控制器中设置,以便在两者中都可用。
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2021-11-28
  • 1970-01-01
  • 2012-09-18
  • 2011-12-20
相关资源
最近更新 更多