Rails合并了两个ActiveRecord :: Relations

时间:2012-04-05 15:18:37

标签: ruby-on-rails ruby-on-rails-3

我有一个“Profile”模型和这个模型的两个ActiveRecord :: Relations。第一关系的SQL请求很大。第二是

Profile.where(:id => 1)

我想首先添加第二个关系。因此,第二个关系将包含第一个prrofile。

我试着

first.merge(second)

但它返回空关系。 Rails版本是3.2.2 当然,结果也应该是关系。我需要将.limit()和.paginate()添加到这个关系中。

2 个答案:

答案 0 :(得分:2)

您可以将其他.where子句添加到现有关系中,因此:

relation = Thing.joins(:associated_things => [:users, :still_more_things]).where(:condition => true)
new_relation = relation.where(:id => 1)

这将使用AND将新的'where'与任何现有的'where'结合起来。 ActiveRecord :: Relation不支持使用OR加入'wheres',如果你需要这样做,请查看Squeel(https://github.com/ernie/squeel),如果你使用的是Rails 3.1+或meta_where( https://github.com/ernie/meta_where)3.0。

答案 1 :(得分:0)

合并将使用合并关系中的值覆盖第一个关系中相同键的值。