If I showed you a snippet from a form view, you’d probably recognize all the parts:
<div class="field"> <%= f.label :first_name %><br /> <%= f.text_field :first_name %> </div> <div class="field"> <%= f.label :last_name %><br /> <%= f.text_field :last_name %> </div> <div class="actions"> <%= f.submit %> </div>
You’d probably guess that the User model has at least two attributes: first_name and last_name. You’d normally be right, but that doesn’t have to be the case. What if I want the database to store first and last names separately, but I want the form to let them type their full name, and I’d split it up behind the scenes? Something like this:
<div class="field"> <%= f.label :full_name, 'Name' %><br /> <%= f.text_field :full_name %> </div>
It’s easy to do, just by adding accessor methods to our model, like so:
class User < ActiveRecord::Base
def full_name
"#{first_name} #{last_name}"
end
def full_name= name
self.first_name, self.last_name = name.split(/\s+/, 2)
end
end
In the example above, we have a getter that spits out the first and last name put together. We also have a setter, that tries to intelligently split a full name into its parts.
Now that there is a full_name and full_name= method in our model, we can use it in our forms like any other attribute. This is because the attributes themselves are just sets of accessor methods that are added to your model by ActiveRecord, built using the database schema for that model’s table.
In other words, if your model’s table has a first_name field, ActiveRecord will automatically create the first_name and first_name= methods for you. It’s these methods (called accessors) that Rails form builders look for, whether they’re attributes stored in the database or not.
Tags: accessors, attributes, form builder, forms, getters, Rails, Ruby, ruby on rails, setters

December 18, 2010 at 3:58 am |
Ryan Bates Railscasted about this in 2007 :)
http://asciicasts.com/episodes/16-virtual-attributes
http://railscasts.com/episodes/16-virtual-attributes
December 18, 2010 at 9:10 pm |
He sure did – and he’s one of my favorite sources since I learn better from visual demonstrations than text descriptions. In fact, you’d be hard-pressed to find a topic that hasn’t been blogged about, by people more important than me :)
But just about everybody has a slightly different angle. I enjoy playing around with code in irb and console, and providing fully working sample applications when I can. I try to answer the questions that come up most often in forums and Q/A sites. That way, I can answer those questions quickly with a link that gives the asker everything they need.