Overriding to_s - Inserting a model directly into a view

<%= @foo %> => #<Foo:0x007fa874102948>


The above happens constantly right? If you want to be able to insert a record into your views directly without having to worry about which column or function holds your functions view string then you need to override to_s.

foo.to_s

def to_s
  name
end

The above will cause <%= @foo %> to insert @foo.name into your view or anywhere else your record is inserted as a string.

aliasing

You can also use aliasing to handle this

alias to_s name


This is functionally identical to the above.

Thanks for subscribing!
Like what I'm doing? Subscribe and I'll let you know when I write new stuff.
Want to unsubscribe?
Subscribe