Ruby on rails 如何在ActiveRecord中强制计算子查询在每次访问时都有许多条件

Ruby on rails 如何在ActiveRecord中强制计算子查询在每次访问时都有许多条件,ruby-on-rails,activerecord,has-many,Ruby On Rails,Activerecord,Has Many,模型: 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 问题是子查询(Spot.where('un

模型:

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
问题是子查询(
Spot.where('unid\u id不为null')
/
(487238889,-1)
)通常不能反映几秒钟前插入
Spot
的新记录。并在访问关系的行(
pp Spot.where('unid\u id不为null')
上进行调试,生成正确的记录集,包括新的记录集

在我看来,如果子查询表达式结果是缓存的,但我必须承认,我不太理解这里隐藏的逻辑

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

使用:

@venue.reload
在访问关联之前,应使用以下方法进行操作。

@venue.reload

在访问关联之前,它应该是有效的。

我放弃了关系方法,选择了如下的查询方法解决方案:

  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答案的评论,了解我选择此解决方案的详细原因。

我放弃了关系方法,选择了如下查询方法解决方案:

  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答案的评论。

谢谢Rob。我不喜欢这种方法的地方是开发人员需要遵守纪律。当然,您可以将其包装到一个模型方法中,但这将使不需要的“错误”关系仍然可以访问。在这种情况下,我宁愿放弃关系方法,而选择简单的查询方法。谢谢Rob。我不喜欢这种方法的地方是开发人员需要遵守纪律。当然,您可以将其包装到一个模型方法中,但这将使不需要的“错误”关系仍然可以访问。在这种情况下,我宁愿放弃关系方法,而选择简单的查询方法。