B
B
badcluster2016-03-25 23:25:16
Ruby on Rails
badcluster, 2016-03-25 23:25:16

How to make a :includes query via a belongs_to relation with conditions on each table?

There is a certain user Ivan.
You need to download all of Ivan's undeleted and unblocked comments that are left for unblocked and undeleted posts.

User
has_many :posts
has_many: comments

Post
belongs_to :user
has_many :comments
scope :active, -> { where(deleted: false, blocked: false) }

Comment
belongs_to :user
belongs_to :post
scope :active, -> { where(deleted: false, blocked: false) }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
CAMOKPYT, 2016-03-25
@badcluster

Comment.includes(:user, :post)
.where(posts: { deleted: false, blocked: false })
.where(comments: { deleted: false, blocked: false })
.where(users: { name: 'Ivan' })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question