难以在Rails中获取多个记录的参数

时间:2017-10-10 02:14:19

标签: ruby-on-rails

我正在使用三个独立的模型,我们称之为:管理员,产品和评论。产品有许多评论和评论属于产品,而管理员是独立的。如果产品或评论没有帮助或被视为垃圾邮件,则该网站的任何访问者都可以选择将其标记为待审核。在管理员控制面板中,管理员可以查看相关产品和评论,然后编辑或删除它们。我可以显示用户标记的评论和产品,但我无法一起显示;例如,假设用户标记了我能够看到它的评论,但我不知道它所属的产品,因为通常每当我尝试访问它所选择的产品记录时。知道这些参数是什么。由于@reviews = Review.where("flag > ?", 0).order("flag DESC")会返回所有标记的评论,因此通常会有多个评论,因此只是说@product = Product.find(id: @reviews.product_id)无法工作,但我相信我需要这样的内容,可以应用于每个单独的评论因为它在使用@reviews.each do |review|

显示之前循环遍历所有标记的评论

admin_controller

def show
   @Admin = Admin.find(params[:id])
   @products = Product.where("flag > ?", 0).order("flag DESC")
   @reviews = Review.where("flag > ?", 0).order("flag DESC")
   @singleProduct = Product.find(id: Review.product_id)  # this is the line that I'm not quite sure of, I want to be able to grab each review.product_id as they loop through on the show.html.erb page to show what product goes with the review.  I realize that calling @reviews.product_id would return multiple ids since there are, theoretically, more then one reviews with flags.
end

Show.html.erb

      <% if @review.blank? %>
         Nothing to review!
      <% else %>
      <div class="list-group">
        <ul class="list-unstyled">
        <% @reviews.each do |review| %>
            <li class="list-group-item">  <%= review.comment %> Review Flagged:
              <%= pluralize(review.flag, 'time', plural: 'times') %>.   <%=  @singleProduct.name   #Again, I'm not sure how to implement this but I want it to grab the product_id of each @review as |review| loops to show however many flagged reviews there are.%>
 <%= link_to 'View',  product_review_path(Product, review) %>

               <%= link_to 'Delete',  product_review_path(Product, review), method: :delete, data: {confirm: "Are you sure you want to delete this review?"} %> </li>
            <% end %>

        </ul>
      </div>
      <% end %>

1 个答案:

答案 0 :(得分:1)

听起来你指的是所谓的eager loading。当您最初获取Review记录时,您还可以获取其Product数据,这样当您遍历评论并调用其相关产品时,它就不需要再次调用数据库。但是,我对你在模特联想中的选择感到有些困惑,所以我可能会错误的尝试。

# controller
def show
  @Admin = Admin.find(params[:id])
  @products = Product.where("flag > ?", 0).order("flag DESC")
  @reviews = Review.includes(:products).where("flag > ?", 0).order("flag DESC")
end


# show.html.erb
<% if @review.blank? %>
  Nothing to review!
<% else %>
  <div class="list-group">
    <ul class="list-unstyled">
    <% @reviews.each do |review| %>
      <li class="list-group-item">  <%= review.comment %> Review Flagged:
          <%= pluralize(review.flag, 'time', plural: 'times') %>. <%=  @review.product.name %>
          <%= link_to 'View',  product_review_path(Product, review) %>
          <%= link_to 'Delete',  product_review_path(Product, review), method: :delete, data: {confirm: "Are you sure you want to delete this review?"} %>
      </li>
    <% end %>
    </ul>
  </div>
<% end %>