-
Notifications
You must be signed in to change notification settings - Fork 277
Add model virtual attribute
Richard Huang edited this page Aug 15, 2010
·
4 revisions
Please go to http://rails-bestpractices/posts/4-add-model-virtual-attribute
Before:
<% form_for @user do |f| %>
<%= text_field_tag :full_name %>
<% end %>
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.first_name = params([:full_name]).split(' ', 2).first
@user.last_name = params([:full_name]).split(' ', 2).last
@user.save
end
end
After:
class User < ActiveRecord::Base
def full_name
[first_name, last_name].join(' ')
end
def full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end
end
<% form_for @user do |f| %>
<%= f.text_field :full_name %>
<% end %>
class UsersController < ApplicationController
def create
@user = User.create(params[:user])
end
end