7urkm3n
7urkm3n

Reputation: 6311

Filtering "Product review" if the exist in Rails

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

Answers (1)

fivedigit
fivedigit

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

Related Questions