该模型:
class Venue < ActiveRecord::Base
has_many :free_unids, :class_name => "Unid",
:conditions => ['id not in (?)',
(Spot.where('unid_id is not null').map(&:unid_id) + [-1])]
end
@venue.free_unids
正如我们在日志中看到的,访问会触发对条件本身的评估:
Unid Load (0.4ms) SELECT "unids".* FROM "unids" WHERE "unids"."venue_id" = 79 AND (id not in (4,8723,8889,-1)) ORDER BY id LIMIT 1
问题是子查询(Spot.where('unid_id is not null')
/ )通常不会反映几秒钟前(4,8723,8889,-1)
插入的新记录。Spot
并且在访问关系的那一行进行调试 ( pp Spot.where('unid_id is not null')
) 会产生正确的记录集,包括新的记录。
在我看来,如果子查询表达式结果被缓存了,但我不得不承认我不太了解这里幕后的逻辑......
是否可以在每次访问时强制评估表达式?或者我们需要另一种方法吗?