我的代码工作正常,但我想知道是否有一种简单快捷的方法可以过滤它?
我正在做:“如果current_user
已经有审核,请不要让他审核并隐藏表单”。
products_helper.rb:
def current_user_commented?
@product.product_reviews.each do |p|
current_user.profile.product_reviews.each do |r|
return false if r == p
end
end
end
show.html.rb:
<% if logged_in? %>
<% if current_user_commented? %>
<%= form_for ([@product, ProductReview.new]) do |f| %>
<div id="star-reviewing"></div>
<div class="form-group">
<%= f.label :comment %>
<%= f.text_field :body %>
</div>
<%= f.submit 'add Comment' %>
<% end %>
<% end %>
<% end %>
答案 0 :(得分:1)
尝试这样的事情:
current_user.profile.product_reviews.where(product: @product).exists?
如果用户已经审核了true
,则会返回@product
。
这个解决方案非常有效,因为它执行单个数据库查询,而不是在Ruby中获取记录和执行相等性检查。
另请阅读exists?
和ActiveRecord queries上的Rails文档。