Rails如何合并两个ActiveRecord::Relation对象?

3

我有一个“Profile”模型,以及该模型的两个ActiveRecord::Relations。第一个关系的SQL请求非常复杂。第二个是

Profile.where(:id => 1)

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

我尝试过

first.merge(second)

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

2个回答

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)。


0

合并操作将第一个关系中相同键的值用合并后关系中的值进行覆盖。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接