Initializing ActiveRecord models
I'm initializing some attributes of my model with after_initialize
callback, but this callback gets called when the record is loaded from database, overwriting the saved values. Here is the model:
class Post < ActiveRecord::Base
serialize :tags
after_initialize :init_tags
def init_tags
write_attribute :tags, []
end
end
Is there any way to do it without changing the callback to
def init_tags
if not read_开发者_如何学Goattribute :tags
write_attribute :tags, []
end
end
Do it like this :
class Post < ActiveRecord::Base
serialize :tags
after_initialize :init_tags
def init_tags
self.tags ||= []
end
end
Which is equivalent to your second solution, only a bit shorter. The save
method isn't called, but it shouldn't be a problem as this will only be used on the first initialization of the model, the value will be filled afterwards.
精彩评论