56

I have a User model and the user has a relationship which is has_many pets. I want to be able to write an ActiveRecord query where I can select all users with a pet that doesn't have a pet.name of "fluffy"

What's the most efficient way to write this using ActiveRecord? Using straight SQL it would look something such as the following:

select id from users INNER JOIN pets ON u.id = pets.user_id WHERE pets.name != "fluffy"

3 Answers 3

77

In rails 4 you can make this even more clear:

User.joins(:pets).where.not(pets: { name: 'fluffy' })
Sign up to request clarification or add additional context in comments.

Comments

66

This should work:

User.joins(:pets).where("pets.name != 'fluffy'")

Also you might want to read the following part (on joins) on the official RoR guidelines.

2 Comments

Please correct me if I'm wrong, but wouldn't it be 'User.joins(:pet)...' - singular - for the symbol parameter?
@jeffdill2 That depends on how the association is defined. If User has_one :pet, for instance, you would be right.
26

The cleanest way without SQL injection vulnerability is using query parameters:

User.joins(:pets).where("pets.name != ?", "fluffy")

Some database drivers will utilize prepared statements for above to reuse database query plan. In such case the database doesn't have to analyze query again when only param value varies.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.