Rails5:我如何使用ActiveRecord" OR"查询"包括"?

时间:2017-02-05 14:52:19

标签: activerecord ruby-on-rails-5

class Parent < ApplicationRecord
  has_many :children

  enum status: {
     status1: 0,
     status2: 1     
  }
end

class Child < ApplicationRecord
  belongs_to :parent
end

# error
# "Relation passed to #or must be structurally compatible. Incompatible values: [:references]"
combination = Parent.status1.or(Parent.status2.includes(:children).where(children: {name: 'ABC'}))

我想获取数据&#34; status1&#34;或者&#34; status2的孩子名为&#39; ABC&#39;&#34;,但发生错误。

2 个答案:

答案 0 :(得分:2)

or method采用具有类似过滤模式的另一种关系,并将其与被调用对象上已有的过滤器相结合。

例如,Parent.status1.or(Parent.status2)会为您提供一组包含status: 1status: 2的记录。

(如果有人不熟悉它,问题中的示例也使用enum,它允许使用值的名称过滤枚举的属性值。{{1在这种情况下,}和#status1分别对应#status2{ status: 0 }。)

为了调用更多关系方法来修改最终结果,您必须在调用{status: 1}的结果上调用它们,如下所示:

#or

根据您的评论,我现在看到您希望记录(包含Parent.status1.or(Parent.status2).includes(:children).where(children: {name: 'ABC'}) )或(包含status1 且具有匹配的status2记录

请注意,为了在children中使用关系(例如where,您必须加入与相关表格where(children: { name: value })。似乎ActiveRecord如果你只使用joins(:children).where(children: { name: value }),我会推断加入,但据我所知,这并没有记录。这就是为什么includes认为两个关系不相容:一个有{{1}在引用列表中,而另一个则没有。

如果您手动将or子句写为字符串,则不会更改引用列表,因此children不会将关系视为不兼容。当您手动编写where子句时,您必须明确使用or

where

答案 1 :(得分:0)

你没有打电话&#34;包括&#34;在决赛或结果上。

parent = Parent.status1.or(Parent.status2)
parent.includes(:chilren).where(children: {name: "ABC"})