【问题标题】:Rails scope where has_one relation has no relationhas_one 关系没有关系的 Rails 范围
【发布时间】:2017-04-06 19:47:56
【问题描述】:

Trip.rb

class Trip < ActiveRecord::Base
  has_one :report
end

报告.rb

class Report < ActiveRecord::Base
  belongs_to :trip
  belongs_to :user
end

旅行首先存在,然后需要报告。创建报告时,它会获得一个trip_id。这种关系在控制台Trip.report 显示正确的报告中起作用

我试图弄清楚如何(大概在 Trip 模型中)通过关系获取没有报告的 Trips 列表

这似乎应该是直截了当的,但我觉得它可能不是。

scope :need_report, -&gt; { where(joins(:report)) }

会给我提供有报告的旅行,但我正试图返回相反的结果。

不确定我是否应该:

  1. 返回连接的反面
  2. 以某种方式嵌套并更新行程的 report_id,以便于调用

【问题讨论】:

    标签: ruby-on-rails ruby scope


    【解决方案1】:

    你可以这样做(返回一个数组):

    scope :no_report, -> { select { |trip| trip.report.blank? } }
    

    也可以获得ActiveRecord::Relation

    scope :no_report, -> { includes(:report).where(report: { id: nil })
    

    【讨论】:

    • 这行得通,但作为一个数组提供,它破坏了范围内的其他方法,即 order、paginate 等。
    • 对不起,漫长的一天。看来我可以在调用 no_report 范围之前运行订单、分页等
    • @RyanMcCrary 修复了答案
    • 那是我试图到达的地方,但无法到达那里。非常感谢!
    • @RyanMcCrary 没问题!
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2010-11-15
    相关资源
    最近更新 更多