Answer the question
In order to leave comments, you need to log in
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
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
<% @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 %>
Answer the question
In order to leave comments, you need to log in
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)
}
}
SELECT "reviews".* FROM "reviews"
WHERE ((
"reviews"."post_id" IN (SELECT "posts"."id" FROM "posts" WHERE "posts"."user_id" = 1)
AND "reviews"."user_id" != 1
))
def show
@user = User.find(params[:id])
@reviews = Review.for_posts_of @user
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question