开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜