ubuntu, ror, jQuery, css, website memo
太嫩, 沒啥心得, 用來紀錄每天學的
2009年10月5日 星期一
has_many , time now, assocation
Do you know when your code runs?
有時候你時候你會發現你在你下的conditions 有關於時間的, 跑起來有點怪怪的
在development 沒問題, 在production 卻不正常
仔細看會發現時間統統都是static 的了, 因為production 並不會每次都去reload class
class Person < ActiveRecord::Base
has_many :posts
has_many :recent_posts, :class_name => 'Post', :conditions => ["created_at > ?", 1.week.ago]
validates_inclusion_of :birth_date, :in => (20.years.ago..13.years.ago),
:message => "You must be a teenager to signup", :on => :create
end
class Post < ActiveRecord::Base
named_scope :recent, :conditions => ["created_at > ?", 1.week.ago]
end
這時候只要換個寫法
#make one with no arguments, just to ensure that the time condition is evaluated whenever the scope is accessed.
class Post
named_scope :recent, lambda { {:conditions => 1.week.ago}}
end
#Active Record will perform that interpolation again at the point where sql is generated
class Person < ActiveRecord::Base
has_many :recent_posts, :class_name => 'Post',
:conditions => "created_at > #{1.week.ago.to_s(:db)}"
end
#Validations can't play any of the clever little games that the other 2 examples can. You'll just have to something like
class Person < ActiveRecord::Base
validate_on_create :is_a_teenager
def is_a_teenager
unless birth_date < 13.years.ago && birth_date > 20.years.ago
...
end
end
end
沒有留言:
張貼留言
較新的文章
較舊的文章
首頁
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言