让关联的model以下拉菜单(select)的形式显示

本文介绍了一个使用Ruby on Rails实现的人员信息管理系统,包括创建模型、迁移数据库、表单验证及下拉菜单选择等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值