3

我有一个“个人资料”模型和这个模型的两个 ActiveRecord::Relations。第一个关系的 SQL 请求非常大。其次是

Profile.where(:id => 1)

我想将第二个关系添加到第一个。因此,第二个关系将包含第一个配置文件。

我试过了

first.merge(second)

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

4

2 回答 2

2

您可以在现有关系上附加额外的 .where 子句,因此:

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

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

于 2012-04-05T16:44:01.303 回答
0

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

于 2012-05-11T20:39:48.843 回答