9

你如何将两个关系加在一起?当我尝试 + 运算符时,它返回一个数组。但我需要它来返回关系。

谢谢,迈克

4

3 回答 3

8

尝试:

new_relation = relation.merge(another_relation)
于 2012-09-06T04:37:46.943 回答
3

您可以使用 Arel 约束添加两个 ActiveRecord::Relation

constraints_1 = Model.matching_one.arel.constraints
constraints_2 = Model.matching_two.arel.constraints

Model.where(constraints_1.and(constraints_2)).class => ActiveRecord::Relation

您也可以使用 or 运算符

Model.where(constraints_1.or(constraints_2)).class => ActiveRecord::Relation

真实例子

constraints_1 = User.where(id: 1..5).arel.constraints
constraints_2 = User.where('id != 2').arel.constraints

User.where(constraints_1.and(constraints_2))

您可以观看有关该http://railscasts.com/episodes/355-hacking-with-arel的精彩截屏

于 2014-03-01T18:59:09.483 回答
2

如果您添加 ActiveRecord::Relation 对象以获得“OR”结果而不是“AND”(通过链接获得“AND”行为),并且您仍然需要结果是 ActiveRecord::Relation 才能发挥出色使用其他一些代码(例如 meta_search)....

def matching_one_or_two
  temp = Model.matching_one + Model.matching_two
  Model.where('id in (?)',temp.map(&:id))
end

当然不是世界上最好的性能,但它会导致 ActiveRecord::Relation 对象指向“或”结果。

您也可以直接将“OR”放入 sql 中,而不是让 Rails 为您生成它,让您的数据库应用程序有机会更好地执行。一个例子:

Model.where("table_name.col = '一个' OR table_name.col = '两个'")

这也将返回一个 ActiveRecord::Relation 对象。

于 2013-05-25T01:27:29.087 回答