添加两个ActiveRecord :: Relation对象
你如何将两个关系加在一起? 当我尝试+运算符时,它返回一个数组。 但我需要它来回归关系。
谢谢,迈克
尝试:
new_relation = relation.merge(another_relation)
您可以使用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
你也可以使用或运营
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的精彩屏幕演示
如果你要添加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
当然不是世界上最伟大的表现,但它导致一个指向’OR’结果的ActiveRecord :: Relation对象。
您也可以直接将“OR”放入sql中,而不是让Rails为您生成它,以便为您的数据库应用程序提供更好的性能。 一个例子:
Model.where(“table_name.col =’one’OR table_name.col =’two’”)
这也将返回一个ActiveRecord :: Relation对象。