MichaelHajuddah
MichaelHajuddah

Reputation: 557

Find all Children where Parent and Grandparent meet certain condition?

I have the following model relationships:

class Author
  has_many :posts
end

class Post
  belongs_to :author
  has_many :comments
end

class Comment
  belongs_to :post
end

I have boolean columns "active" for Authors and "published" for Posts.

I want to find all comments where author.active: true and post.published: true

Could anyone help me out? I'm able to get all Posts from an Author with author.active: true by using a joins statement (this code in the Post model):

joins(:author).where(authors: {active: true})

but I can't seem to figure out how to get all comments where author.active: true and post.published: true.

Upvotes: 0

Views: 937

Answers (1)

usha
usha

Reputation: 29349

This should work

Comment.joins(:post => :author).where("authors.active = true AND posts.published = true" )

or

Comment.joins(:post => :author).where(:post => {:published => true, :author => {:active => true}})

Upvotes: 2

Related Questions