Can't reload ActiveRecord association from controller

余生长醉 提交于 2019-12-18 07:19:29

问题


Spent a working day on this.

I have

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

I also have custom insert_new_users and associate_with(new_users) methods which use multiple INSERT to do their job quickly. Anyway, they work fine. I also have this line at the end of "associate_with" method:

def associate_with
  # mysql INSERT here
  self.users(true) # Should force reload
end

It works as expected when running in test environment (both controller and model tests) and it fails as expected if I remove the true argument, which forces the reload. It also works from script/console in development if I update_attributes the model. But fails in development or production when I'm trying to update_attributes from controller. It simply does not reload associations and I can see it in logs, where it says "CACHE (0.0ms)" for this query.

The weird thing - it worked before and I can't identify the moment it stopped working due to some reasons. I was hoping maybe someone knows how is this possible.


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/966012/cant-reload-activerecord-association-from-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!