Forum: Ruby on Rails Should we override model accessors?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B1d59a804bd67487c964bc505a8eb892?d=identicon&s=25 Thiago Arrais (Guest)
on 2007-01-01 22:20
(Received via mailing list)
I have stumbled across an issue with FormHelper#text_field and thought
it was worth a patch. The ticket (with patch) is here

http://dev.rubyonrails.org/ticket/6908

It seems like my solution can't be applied because the form helper
methods really needs to use the *_before_type_cast methods because
of numerical attributes. (By the way, the actionpack tests do not show
that yet)

The thing is that the problem hit something inside me and I got
thinking:
should we really try to override the default attribute accessors? I
mean,
there are .read and .write_attributes for those of us who want to, but
should we?

What I was originally trying to have was something like

  def title
    result = read_attribute(:title)
    return title_from_name || PLACE_HOLDER_TITLE.t if result.nil? ||
result.empty?
    return result
  end

(Rough translation: in case there isn't a title, generate a default one
based on the name)

But, because of the before_type_cast issue, I had to use something
along
these lines

  def title; title_before_type_cast; end
  def title_before_type_cast
    result = read_attribute(:title)
    return title_from_name || PLACE_HOLDER_TITLE.t if result.nil? ||
result.empty?
    return result
  end

...and that hurts. A lot! Not to mention that it may have introduced
some
subtle bugs that will come back to haunt me in the future.

I could also have tried renaming the db column to db_title or
something, but
that doesn't seem right either. I thought about using something like
validates_*,
but this isn't really a validation. We are just providing some sample
data that
would be tedious for the user to enter in many cases.

Is there any idiomatic solution for that?

Cheers,

Thiago Arrais
This topic is locked and can not be replied to.