robb
robb

Reputation: 294

Building a where and or query in rails 4

I'm trying to build a query that will display posts if featured OR if the post belongs to a user who is auto approved.

I've tried a few variations with not luck. Any ideas?

@posts = Post.includes(users:).where('posts.featured = ? OR users.auto_approved = ?', true, true).order("posts.created_at DESC")

Upvotes: 1

Views: 57

Answers (2)

H Dox
H Dox

Reputation: 675

You should use left_join for this case since you will want to keep posts which are not belonged to any users

@posts = Post.joins('LEFT JOIN users ON users.id = posts.user_id').where('posts.featured = ? OR users.auto_approved = ?', true, true).order("posts.created_at DESC")

Upvotes: 2

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

Try this:

Post.joins(:user).where('posts.featured OR users.auto_approved').order("posts.created_at DESC")

Upvotes: 3

Related Questions