rails scope and joins

廉价感情. 提交于 2019-12-09 17:25:37

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/11622959/rails-scope-and-joins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!