Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails ActiveRecord query using a join

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"

like image 648
randombits Avatar asked Apr 30 '12 22:04

randombits


People also ask

What is join in Ruby on Rails?

Ruby on Rails ActiveRecord Query Interface Joins joins() allows you to join tables to your current model. For ex. User.joins(:posts)

How can we use two databases to a single application Rails?

Rails 6.0 ships with all the rails tasks you need to use multiple databases in Rails. Running a command like bin/rails db:create will create both the primary and animals databases.


2 Answers

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.

like image 58
Amokrane Chentir Avatar answered Sep 17 '22 15:09

Amokrane Chentir


In rails 4 you can make this even more clear:

User.joins(:pets).where.not(pets: { name: 'fluffy' }) 
like image 31
Albin Avatar answered Sep 17 '22 15:09

Albin