问题描述
我已经尝试了所有我认为可以解决的问题,但没有发现任何问题。
I have tried everything i thought would work for this and am turning up nothing.
在轨道3中,我需要找到所有在车上装有CD播放器的用户。汽车有一个用户和一个收音机,一个用户属于汽车,收音机有很多汽车。
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
推荐答案
我假设您的意思是:
汽车有 radio_id
,用户有 car_id
,
,因为收音机有很多汽车,汽车有一个用户。带有外键的表始终位于关系的belongs_to末端。
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'")
这篇关于Rails范围和连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!