views:

34

answers:

1

What is the 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?

+2  A: 

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.

neutrino
If you need to validate the value somehow, you're better off doing your transformations in the attribute accessor.
François Beausoleil