Don P
Don P

Reputation: 63547

Get all records for an active record relationship with a where clause

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

Answers (2)

Alexander Shlenchack
Alexander Shlenchack

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

Athar
Athar

Reputation: 3258

You can achieve it this way, using the exists? method to check if any records exist with a single SQL call (without unnecessary object instantiation as with any? or present?):

@user.posts.includes(:sections).where(sections: {title: "Hello World"}).exists?

Upvotes: 1

Related Questions