HowTo: Virtual Attributes
October 10, 2008 Leave a comment
1) rails howto_use_vitual_attributes
2) cd howto_use_virtual_attributes
3) ruby script/generate scaffold Person first_name:string last_name:string
4) rake db:migrate
5) open up person.rb and add these getter and setter methods
def full_name
[first_name, last_name].join(' ')
enddef full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end
6) edit your new.html.erb file
<%= f.label :full_name %>
<%= f.text_field :full_name %>
Note: full_name is not in the db, it’s just a virtual attribute
7) ruby script/server
8) localhost:3000/people/ (note: not persons
)
Based on Railscasts ep16.