Virtual Attributes

Keep your controllers clean and forms flexible by adding virtual attributes to your model. This very powerful technique allows you to create form fields which may not directly relate to the database.

通过在model里添加虚拟属性,保证controller中的代码整洁和表单的灵活性。这个非常强大的技术允许你创建与数据库非直接相关的表单字段。

还是以注册为例:

注册页面有
First Name___________
Last Name___________
Pasword_____________
现在用一个full_name的虚拟属性来代替First Name和Last Name这两个字段。
首先在视图中将两个text_field改成一个:
<h1>Register</h1>
<% form_for :user, :user=>users_path do |f|%>
<p>
Full Name<br/>
<%=f.text_field :full_name%>
</p>
<p>
Password<br/>
<%= f.password_field :password%>
</p>
<p>
<%= submit_tag 'Register'%>
</p>
<% end %>

full_name是User的一个虚拟属性,它跟first_name和last_name相关联,first_name和last_name是定义在user里的对象属性。也是存储在数据库中的字段。

在model中要定义一个full_name的方法
还要定义一个full_name=(name)的方法
# models/user.rb
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