1

在 Rails 3 中,我可以对关联模型执行查询:

示例 1:

model.associated_models.where(:attribute => 1)

associated_models 是一个模型数组。

是否可以对手动创建的模型数组执行 activerecord 查询?

示例 2:

[Model.create!(attribute: 1), Model.create!(attribute: 2)].where(:attribute => 1)

就像第一个示例中的 associated_models 和模型数组一样,但我想在调用 associated_models 时后台会发生一些事情。

我可以模拟这种行为以使示例 2 正常工作吗?

4

2 回答 2

1

我建议使用 Array#keep_if 来完成这项任务,而不是将数组压缩到 ActiveRecord::Relation 中。

 [Model.create!(attribute: 1), Model.create!(attribute: 2)].keep_if { |m| m.attribute == 1 }

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-keep_if (注意,Array#select! 做同样的事情,但我更喜欢 keep_if 以避免以后阅读时混淆,认为它可能与 sql 选择有关)

于 2012-05-26T08:55:14.740 回答
1

简短的回答是否定的,你不能。Activerecord 范围链为数据库构造查询,这不能解释为任意数组,即使它是像您的示例中那样的 AR 对象数组。

您可以通过适当的数据库范围“模拟”它

Model.where(:id => array_of_ar_objects.map(&:id), :attribute => 1)

(但这是错误的,因为您只想在需要时进行 db 调用)或使用数组搜索:

array_of_ar_objects.select { |model| model.attribute == 1 }

还要注意 model.associated_models 不是一个数组,而是ActiveRecord::Associations::HasManyAssociation一种关联代理。这非常棘手,因为即使它的“类”方法被委托给它被强制的数组,我猜这就是你被误导的原因。

model.associated_models.class == Array
-> true
于 2012-05-26T09:12:40.353 回答