user308096
user308096

Reputation:

rails scope and joins

I have tried everything i thought would work for this and am turning up nothing.

in rails 3, I need to find all users with a cd player in their car. A car has one user and one radio, and a user belongs to a car, and a radio has many cars.

I am stumbling on how I would perform this search via a scope in the user model.

class User  
  belongs_to :car

class Car  
  belongs_to radio
  has_one :user, :dependent => destroy

class Radio  
  has_many :cars

Upvotes: 18

Views: 36594

Answers (2)

Salma Gomaa
Salma Gomaa

Reputation: 1112

Also you can use merge:

Author.joins(:books).merge(Book.available)

Source: https://gorails.com/blog/activerecord-merge

Upvotes: 16

cjhveal
cjhveal

Reputation: 5791

I am assuming that you mean this: Car has radio_id, User has car_id, since a radio has many cars and car has one user. The table with the foreign key always is on the belongs_to end of the relationship.

Without really knowing the structure you're looking for, something like the following should work:

scope :with_cd_player, joins(:cars).where('cars.radio_id is not null')

if there is a category column on the radio, the following would work.

scope :with_cd_player, joins(:car => :radio).where('cars.radio_id is not null').where("radios.category = 'cd_player'")

For Rails Version >= 4:

scope :with_cd_player, -> { joins(:cars).where.not(cars: { radio_id: nil }) }

Upvotes: 34

Related Questions