我有这个:
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 调用中使用该关联或通过包含急切加载关联吗?
似乎在预加载器/急切加载上下文中,条件 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