[英]Can I use ActiveRecord::Associations::Preloader / eager loading to load a has_one relationship with dynamic conditions?
I've got this: 我有这个:
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
I would like to do this: 我想这样做:
users = User.limit(10)
ActiveRecord::Associations::Preloader.new(users, [:profile => :latest_action]).run
or this: User.includes(:profile => :latest_action).limit(10).all 或者:User.includes(:profile =>:latest_action).limit(10).all
However, this fails: 但是,这失败了:
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>
This works when I'm dealing with a single record: 这在我处理单个记录时有效:
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
Can I use a Proc to generate dynamic conditions on a has_one association and use that association in an ActiveRecord::Associations::Preloader call or with eager loaded associations via include? 我是否可以使用Proc在has_one关联上生成动态条件,并在ActiveRecord :: Associations :: Preloader调用中使用该关联,或者通过include使用eager加载的关联?
It seems like in the in pre-loader / eager loading context, self in the conditions proc is a class not an instance. 看起来在预加载器/预先加载的上下文中,条件proc中的self是一个类而不是实例。
I am on Rails 3.2.13 我在Rails 3.2.13上
Note I realize I could load the association like this, but I can't use that with the preloader 注意我意识到我可以像这样加载关联,但我不能将它与预加载器一起使用
class Profile
has_many :actions do
def latest
where("action_at <= ?", proxy_association.owner.timezone.now.to_date)
end
end
end
The problem is that self
isn't your object in the has_many
, it's the association proxy. 问题是
self
不是你在has_many
的对象,它是关联代理。 If you want the profile
object that is referenced in the association, it should be owner
(though this is slightly dependent on the version of Rails you're running -- check the documentation for Rails association extensions for more details). 如果您想要关联中引用的
profile
对象,它应该是owner
(尽管这稍微取决于您正在运行的Rails的版本 - 有关更多详细信息,请查看Rails关联扩展的文档 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.