Search code examples
sqlruby-on-railsactiverecord

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

Solution

  • 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 }) }