我已经尝试了所有我认为对此有效的方法,但一无所获。
在Rails3中,我需要找到车里有cd播放器的所有用户。一辆车有一个用户和一个收音机,一个用户属于一辆车,一个收音机有很多辆车。
我不知道如何通过用户模型中的作用域来执行这个搜索。
class User
belongs_to :car
class Car
belongs_to radio
has_one :user, :dependent => destroy
class Radio
has_many :cars发布于 2012-07-24 10:04:29
我假设你的意思是: Car有radio_id,user有car_id,因为一台收音机有多辆车,而car只有一个用户。带有外键的表始终位于关系的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'")对于Rails版本>= 4:
scope :with_cd_player, -> { joins(:cars).where.not(cars: { radio_id: nil }) }https://stackoverflow.com/questions/11622959
复制相似问题