![](/img/trans.png)
[英]eager load ActiveRecord polymorphic associations that are 'has_one'
[英]Can I use ActiveRecord::Associations::Preloader / eager loading to load a has_one relationship with dynamic conditions?
我有这个:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
has_one :latest_action,
:class_name=>'Action',
:conditions=> Proc.new {["action_at <= ?", self.timezone.now.to_date]},
:order=>"action_at desc"
end
create_table "actions", :force => true do |t|
t.date "action_at"
t.datetime "created_at"
t.datetime "updated_at"
end
我想这样做:
users = User.limit(10)
ActiveRecord::Associations::Preloader.new(users, [:profile => :latest_action]).run
或者:User.includes(:profile =>:latest_action).limit(10).all
但是,这失败了:
User Load (0.9ms) SELECT "users".* FROM "users" LIMIT 2
Profile Load (0.8ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" IN (133622, 133623)
NoMethodError: undefined method `timezone' for #<Class:0x007fc5992152f8>
这在我处理单个记录时有效:
User.last.profile.latest_action
User Load (0.8ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
Profile Load (0.5ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = 242222 LIMIT 1
Action Load (0.6ms) SELECT "actions".* FROM "actions" WHERE "actions"."profile_id" = 231220 AND (action_at <= '2013-08-27') ORDER BY action_at desc LIMIT 1
我是否可以使用Proc在has_one关联上生成动态条件,并在ActiveRecord :: Associations :: Preloader调用中使用该关联,或者通过include使用eager加载的关联?
看起来在预加载器/预先加载的上下文中,条件proc中的self是一个类而不是实例。
我在Rails 3.2.13上
注意我意识到我可以像这样加载关联,但我不能将它与预加载器一起使用
class Profile
has_many :actions do
def latest
where("action_at <= ?", proxy_association.owner.timezone.now.to_date)
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.