【问题标题】:rails scope and joins轨道范围和连接
【发布时间】:2012-07-24 01:41:07
【问题描述】:

我已经尝试了所有我认为可行的方法,但没有任何结果。

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

我对如何通过用户模型中的范围执行此搜索感到困惑。

class User  
  belongs_to :car

class Car  
  belongs_to radio
  has_one :user, :dependent => destroy

class Radio  
  has_many :cars

【问题讨论】:

  • 如果您想获得帮助,您应该说明您的数据库架构是什么样的。
  • “一个用户属于一辆车,一个收音机有很多辆车”这是一个奇怪的模型。你能显示一些代码吗?

标签: sql ruby-on-rails activerecord


【解决方案1】:

我假设您的意思是: 汽车有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'")

对于 Rails 版本 >= 4:

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

【讨论】:

  • 从 Rails 4 开始,范围主体需要是可调用的,所以它是:scope :with_cd_player, -> { joins(:cars).where('cars.radio_id is not null') }
猜你喜欢
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
相关资源
最近更新 更多