Rails scope and integrates

I tried everything that I thought would work for this, and do not raise anything.

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

I am stumbling over how to perform this search using a scope in a user model.

class User  
  belongs_to :car

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

class Radio  
  has_many :cars
+5
source share
1 answer

I assume that you mean this: The car has radio_id, The user has car_id, since the radio has many cars, and the car has one user. A table with a foreign key is always on the belongs_ side at the end of the relationship.

, , :

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

, .

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

All Articles