开发者

Should I be using callbacks or should I override attributes?

What is the开发者_如何学JAVA more "rails-like"? If I want to modify a model's property when it's set, should I do this:

  def url=(url)
    #remove session id
    self[:url] = url.split('?s=')[0]
  end

or this?

  before_save do |record|
    #remove session id
    record.url = record.url.split('?s=')[0]
  end

Is there any benefit for doing it one way or the other? If so, why? If not, which one is generally more common?


Obviously these two have different use-cases.

The first one should be done if you need to access the modified attribute before the record is saved. For example, you want to set the url and at once check the modified value against some condition before saving it to DB.

The second one fits if you only want to do something with the attribute just before saving to the database. So if you access it between the moment of setting and the moment of saving, you'll get the unmodified value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜