RSS icon Home icon
  • Rails has_many Time.now gotcha

    Posted on October 7th, 2009 dryan No comments

    It’s one of those face palm moments for me, but don’t use has_many in your rails models if it’s time dependent data. In the production environment the Time.now will be the time the environment loads the class, which is only once per server start. Keep in mind your code will work in development and test mode. So basically the solution is to move those has_many statements into a function.

    has_many :recent_stuff, :conditions => ["starts_at =?", Time.now]

    becomes…

    def recent_stuff
    timenow = Time.now
    self.find(:all, :conditions => ["starts_at = ?", timenow])
    end

    Leave a reply