Reputation: 6311
My code works fine, but I want to know if there is an easy and faster way to filter it?
I'm doing: "If current_user
already has a review, do not let him review and hide form".
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 %>
Upvotes: 0
Views: 150
Reputation: 18682
Try something like this:
current_user.profile.product_reviews.where(product: @product).exists?
This returns true
if the user has already reviewed @product
.
This solution is quite efficient as it executes a single database query rather than fetching records and performing equality checks in Ruby.
Also read the Rails documentation on exists?
and ActiveRecord queries.
Upvotes: 1