Can't reload ActiveRecord association from controller

后端 未结 3 1274
逝去的感伤
逝去的感伤 2020-12-20 05:48

Spent a working day on this.

I have

class Box
  has_many :users, :through => :subscriptions
end

I also have custom insert_

相关标签:
3条回答
  • 2020-12-20 06:36

    So far I've been able to trick AR with the following:

    def associate_with
      # mysql INSERT here
      @users = self.users.find(:all, :conditions => ['users.id IS NOT NULL'])
    end
    
    def users
      @users || self.users
    end
    
    0 讨论(0)
  • 2020-12-20 06:44

    You're seeing the effects of the ActiveRecord SQL query cache.

    Either wrap the pre-INSERT references to the users association in a call to uncached

    self.class.uncached do
      # ...
    end
    

    This will stop ActiveRecord from caching the results of any queries inside the block. If you have code in many places, this may be annoying.

    You can also clear the cache after you are done with your inserts by calling connection.clear_query_cache.

    0 讨论(0)
  • 2020-12-20 06:53

    The only way I've been able to fully clear the cache is to call reload. For example, you could call

    User.reload

    and it should force a cache clear including of any relations or associations.

    0 讨论(0)
提交回复
热议问题