Forum: Ruby on Rails text_field and overridden methods

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.
19062fbe329ec034ef54729fa9789e8d?d=identicon&s=25 Mark Veerman (Guest)
on 2007-07-30 16:41
(Received via mailing list)
Hello,

I've got a model with an attribute that I've overridden -- or at least
defined an implementation for. It seems that when I call
form.text_field :foo, it's grabbing foo out of the attributes hash in
the object rather than calling the method. I can get around this by
using text_field_tag :foo, @object.foo.

Is that cool, or is there a better way? It seems interesting that
text_field would grab stuff directly out of the attributes hash,
thereby assuming my implementation. If they called the method 'foo' it
would preserve my implementation. Then, if there wasn't an
implementation, ActiveRecord would step in and handle things.

Thanks!
Mark
D69d23d8e811e8ab2a8593380d6ede63?d=identicon&s=25 Jeff Emminger (jemminger)
on 2007-07-31 04:55
(Received via mailing list)
what does your implementation look like?

something like this ought to work as expected:

class Foo
 def foo
  "custom value of #{self[:foo]}"
 end
end
19062fbe329ec034ef54729fa9789e8d?d=identicon&s=25 mveerman (Guest)
on 2007-08-01 22:15
(Received via mailing list)
Hello,

On Jul 30, 10:54 pm, jemminger <jemmin...@gmail.com> wrote:
> what does your implementation look like?
>
> something like this ought to work as expected:
>
> class Foo
>  def foo
>   "custom value of #{self[:foo]}"
>  end
> end

Thanks for the response. That's exactly what I was doing. I have a
plugin that defines an implementation for foo like you describe.

We did figure out what was going on though.  For each model attribute
in Rails there's another method called value_before_type_cast. In the
case of your example: the attribute foo would have two Rails
'MethodMissing' getters: foo, and foo_before_type_cast.  It seems that
the text_field API uses the latter, so my implementation for foo was
never called.  We solved the problem by implementing
foo_before_type_cast and having it call through to foo. I'm not sure
if that's the best way, but it works and makes sense.

I don't really know why there is that other before_type_cast method,
or why text_field seems to prefer it.

Thanks,
Mark
This topic is locked and can not be replied to.