我是Rails的新手,我正在尝试做一些查询,但我失败了。我有两个ActiveRecord::Base,如下所示:
class A < ActiveRecord::Base
has_many :bs
end
和
class B < ActiveRecord::Base
belongs_to :a
end
在这些行中,B的每一行(与该A相关),其中B有一些任意日期(作为参数传递)。
我已经尝试使用范围、连接、包含、合并,但似乎没有任何效果。我想要所有的 A,A.bs 只返回该特定日期的 B。在许多情况下,A 在特定日期没有 B,即便如此,我也希望返回 A,A.bs 为空。
这可能吗?
谢谢
您可以使用
.includes
执行包含 A 中的记录的LEFT OUTER JOIN
(左),即使 B 中没有匹配项(右)。
@a = A.includes(:bs).where(bs: { due_at: Date.yesterday }).find(params[:id])
@bs = @a.bs # will use the eager loaded collection
- http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables