Reputation: 63547
A user has many posts. A post has many sections.
I want to check if a user has any posts with sections titled "Hello World".
What is the correct way to do this in Rails 4?
What I tried: sections = @user.sections.where(title: "Hello World")
Error: NoMethodError: undefined method 'sections' for #<User::ActiveRecord_Relation:0x007f8781fa9a19>
Upvotes: 0
Views: 636
Reputation: 3869
You can do it using :joins:
@user.posts.joins(:sections).where(sections: {title: "Hello World"}).any?
Here will be used INNER JOIN and this generates sql-query:
SELECT COUNT(*) FROM "posts"
INNER JOIN "sections" ON "sections"."post_id" = "posts"."id"
WHERE "posts"."user_id" = $1 AND "sections"."title" = "Hello World"
Upvotes: 0