我有一个具有默认范围的模型
class SomeModel < ActiveRecord::Base
attr_accessible :id, :name
default_scope includes(:relation)
after_initialize :do_something_with_relation
def do_something_with_relation
self.name += self.relation.name
end
end
我在这里尝试做的是将关系的名称附加到SomeModel对象。我添加了一个默认范围来支持预先加载。但由于某种原因,尽管需要加载,但是使用where子句获取的每个对象都会获取该关系。
SomeModel.where("name LIKE '%some name%'").all
SomeModel Load (0.2ms) SELECT `some_models`.* FROM `some_models`
SomeRelation Load (0.2ms) SELECT `some_relations`.* FROM `some_relations` WHERE `some_relations`.`id` = some_id LIMIT 1
SomeRelation Load (0.2ms) SELECT `some_relations`.* FROM `some_relations` WHERE `some_relations`.`id` = some_id LIMIT 1
SomeRelation Load (0.2ms) SELECT `some_relations`.* FROM `some_relations` WHERE `some_relations`.`id` = some_id LIMIT 1
SomeRelation Load (0.2ms) SELECT `some_relations`.* FROM `some_relations` WHERE `some_relations`.`id` = some_id LIMIT 1
这是一个优先问题吗?在对象初始化之后发生了急切的加载?如果有,有办法在预先加载完成后触发after initialize回调吗?
我期待的结果是
SomeModel Load (0.2ms) SELECT `some_models`.* FROM `some_models`
SomeRelation Load (0.2ms) SELECT `some_relations`.* FROM `some_relations` WHERE `some_relations`.`id` IN (some_id, some_other_id, ...)
我正在使用Rails 3.2
答案 0 :(得分:1)
after_initialize
,因此您只需在获取所有内容后手动调用自定义方法