简体   繁体   English

rails 作用域和连接

[英]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.在 rails 3 中,我需要找到所有在车里有 CD 播放器的用户。 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

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.我假设你的意思是:汽车有radio_id ,用户有car_id ,因为收音机有很多汽车而汽车只有一个用户。 The table with the foreign key always is on the belongs_to end of the relationship.具有外键的表始终位于关系的 belongs_to 端。

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:对于 Rails 版本 >= 4:

scope :with_cd_player, -> { joins(:cars).where.not(cars: { radio_id: nil }) }

Also you can using "merge" https://gorails.com/blog/activerecord-merge您也可以使用“合并” https://gorails.com/blog/activerecord-merge

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM