【问题标题】:Rails scope lambda excluding fields with null valuesRails 范围 lambda 不包括具有空值的字段
【发布时间】:2012-08-21 17:29:32
【问题描述】:

我有一个范围来查找 call_status 处于打开状态且 unit_id 为 nil 的呼叫记录。

scope :unassigned_calls, where(:call_status => "open", :unit_id => nil).order("id ASC")

我最近设置了一个 has_many 关系,其中 unit_id 不再用于调用模型,而是在 call_unit 模型连接表上使用了一个名为 unit_ids 的字段。

如何将范围或 lambda 表达到它包含连接表中的 unit_ids 的位置?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 join scope


    【解决方案1】:

    我不相信 AREL 允许您调用外部联接。尝试写出 SQL

    scope :unassigned_calls, joins("left outer join call_unit on call.id=call_unit.call_id").where("call_unit.unit_id is null").order("id ASC")
    

    我在这里假设连接表有一个 call_id 列,这可能不准确,但希望它能为您提供必要的框架

    【讨论】:

    • 如果你经常做外部连接并且不喜欢写上面那个 SQL 片段,你可以使用squeel,它可以让你灵活地做一些类似的事情:``` scope : unassgined_calls,加入{call_unit.outer ```
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2012-05-19
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多