rails scope和join

我已经尝试了一切我认为可以为此工作的东西,而且我什么都没有。

在rails 3中,我需要在他们的汽车中找到所有有cd播放器的用户。 汽车有一个用户和一个收音机,用户属于汽车,收音机有很多汽车。

我对如何通过用户模型中的作用域执行此搜索感到磕磕绊绊。

class User belongs_to :car class Car belongs_to radio has_one :user, :dependent => destroy class Radio has_many :cars 

我假设你的意思是:汽车有radio_id ,用户有car_id ,因为收音机有很多车,而且车有一个用户。 具有外键的表始终位于关系的belongs_to末尾。

如果没有真正了解您正在寻找的结构,以下内容应该可行:

 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'")