1. 先使用rails命令行generate scaffold来生成将要用到的各个组件。
a) Sex
rails generate scaffold Sex name:string
b) Person
rails generate scaffold Person name:string birthday:date salary:decimal sex:references
2. 生成数据库表:
rails db:migrate
3. 修改页面: 主要是在edit页面上让sex以下拉菜单的形式显示。
a) app/views/people/_form.html.erb
<%= form_for(@person) do |f| %>
<% if @person.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@person.errors.count, "error") %> prohibited this person from being saved:</h2>
<ul>
<% @person.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :birthday %><br />
<%= f.date_select :birthday %>
</div>
<div class="field">
<%= f.label :salary %><br />
<%= f.text_field :salary %>
</div>
<div class="field">
<%= f.label :sex %><br />
<%= f.select(:sex_id, Sex.all.map { |sex| [sex.name, sex.id] }, :prompt => true) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
b) app/views/people/index.html.erb
<h1>Listing people</h1>
<table>
<tr>
<th>Name</th>
<th>Birthday</th>
<th>Salary</th>
<th>Sex</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @people.each do |person| %>
<tr>
<td><%= person.name %></td>
<td><%= person.birthday %></td>
<td><%= person.salary %></td>
<td><%= person.sex.name %></td>
<td><%= link_to 'Show', person %></td>
<td><%= link_to 'Edit', edit_person_path(person) %></td>
<td><%= link_to 'Destroy', person, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Person', new_person_path %>
c)app/views/people/show.html.erb<p id="notice"><%= notice %></p>
<p>
<b>Name:</b>
<%= @person.name %>
</p>
<p>
<b>Birthday:</b>
<%= @person.birthday %>
</p>
<p>
<b>Salary:</b>
<%= @person.salary %>
</p>
<p>
<b>Sex:</b>
<%= @person.sex.name %>
</p>
<%= link_to 'Edit', edit_person_path(@person) %> |
<%= link_to 'Back', people_path %>
4. 修改model : person.rb 如下:
class Person < ActiveRecord::Base
belongs_to :sex
validates :sex_id, :presence => true
validates :name, :uniqueness => true
end