1

该模型:

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')) 会产生正确的记录集,包括新的记录。

在我看来,如果子查询表达式结果被缓存了,但我不得不承认我不太了解这里幕后的逻辑......

是否可以在每次访问时强制评估表达式?或者我们需要另一种方法吗?

4

2 回答 2

1

我放弃了关系方法,而选择了这样的查询方法解决方案:

  def free_unids
    return Unid.where(
      'venue_id = ? and id not in (?)', 
      id, 
      (Spot.where('unid_id is not null').map(&:unid_id) + [-1])).
      order('id')
  end

有关我为什么选择此解决方案的详细信息,请参阅我对 Rob 的回答的评论。

于 2013-06-06T12:54:27.433 回答
0

使用:

@venue.reload

在访问关联之前应该可以工作。

于 2013-05-29T09:49:28.687 回答