User9123
User9123

Reputation: 55

ActiveRecord: How to query all 'children_model' of 'parents_model' where 'parents_model.something = X?

Community has_many posts

Posts belong_to Community

Community.featured is boolean

I want to retrieve all Posts where Community.featured = true

I've tried this, but I can't get the query to work: Community.joins(:post).where('community.featured=true')

Upvotes: 0

Views: 55

Answers (2)

ADMAT Bandara
ADMAT Bandara

Reputation: 61

I would recommend using "includes" behalf of "joins" because If we go through Rails documenting, it clearly says — ‘With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries’. When we need data to be used from associated tables, includes must be used.

Post.includes(:community).where(communities: {featured: true})

Or

You could write a scope in the Community Model

scope :show_featured_communities, -> {
  where(features: true)
}

And Call it as

Community.show_featured_communities.includes(:post)

Upvotes: 1

Anand
Anand

Reputation: 6531

There seems some typo, please try this -

Post.joins(:community).where("communities.featured= ?", true)

Or

Post.joins(:community).where(communities: {featured: true})

Note - Always use table_name in plural form in the query i.e (communities.featured instead of community.featured)

Upvotes: 1

Related Questions