【问题标题】:Rails has_one conditionsRails has_one 条件
【发布时间】:2016-07-14 18:03:52
【问题描述】:

我在驱动表中定义了 has_one 关系

has_one :current_haul 

它与运输表相关联。
以及 hauls table 和 drivers table,他们都有organization_id

我想申请这样的条件

select * 
from drivers 
join hauls on drivers.organization_id=hauls.organization_id
 and drivers.current_haul_id= hauls.id  

我可以把这个条件放在has_one修饰符中吗?

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您可以这样做,只需在Haul 表上添加一个布尔列。也许您需要一个唯一的索引来确保您在任何给定时刻都没有多个 current

has_one :current_haul, -> { where(current: true) }, class_name: 'Haul'

【讨论】:

    【解决方案2】:

    您可以在驱动程序模型中添加如下所示的关联。

    has_one :current_haul, -> { where(current: true).first }, class_name: 'Haul'

    这里我假设你的 Haul 模型中存在一个布尔位来检查当前状态。

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多