Rails Tip: to_s

I haven’t posted much recently as I’ve been very busy at work (more on that later) so I thought I would post another Rails tip.


## Model
class Person < ActiveRecord::Base
def to_s
self.title
end
end

# View
link_to person

# Output
<a href=\"http://foo.bar/person/1\">Zach Inglis</a>

View Pastie

Furthermore you could extend it like this:

## Model
class Person < ActiveRecord::Base
def to_s
self.title
end

def to_param
self.slug
end
end

# View
link_to person

# Output
<a href=\"http://foo.bar/person/zach-inglis\">Zach Inglis</a>

View pastie

1 Response to “Rails Tip: to_s”


  1. Gravatar Icon 1 Matt Sears

    Great tip Zach. I just used this for my own project. Thanks!

Comments are currently closed.