D
D
dexdev2014-02-03 22:03:01
Ruby on Rails
dexdev, 2014-02-03 22:03:01

How to exclude certain records in a query?

Good day to all!
There are Posts, posts have reviews, so you need to show these same reviews on the pages of users, everything works, but I would like to exclude the review if it was written by the user who displays it, how to do this?
Post.rb

has_many :reviews
belongs_to :executor, class_name: 'User', :foreign_key => 'executor_id'
end

Review.rb
belongs_to :post
  belongs_to :user
end

class CreateReviews < ActiveRecord::Migration
  def change
    create_table :reviews do |t|
      t.text :body
      t.references :post, index: true
      t.references :user, index: true

      t.timestamps
    end
  end
end

I insert in the view
<% @user.executors.includes(:reviews).each do |post| %>
    <% post.reviews.each do |review| %>
          <%= avatar_for review.user, :size => "50x50" %>
        <%= link_to review.user.name, review.user %>
        отзыв о выполнении задания: <%= link_to post.name, post %>  
          <%= review.body %>
    <% end %>
  <% end %>

Now everything is working, but on the page on which the review is displayed, there is a review of the user who wrote this very user, but it should not be there, there should only be reviews from other users, tell me how to do it? how to register an exception, that is, exclude the user but leave other reviews, or can make another scheme?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tonis Simo, 2014-02-04
@estum

First, as usual, I advise everyone to squeel gem .
In review.rb :

scope :for_posts_of, ->(_author){
  where{
    (post_id >> _author.posts.select{id}) & 
    (user_id != _author.id)
  }
}

It comes up with a query like:
SELECT "reviews".* FROM "reviews"
WHERE ((
  "reviews"."post_id" IN (SELECT "posts"."id" FROM "posts" WHERE "posts"."user_id" = 1)
  AND "reviews"."user_id" != 1
))

In the controller, you can now:
def show
  @user = User.find(params[:id])
  @reviews = Review.for_posts_of @user 
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question