rails 3 的一对一的关联

主要将 ActiveRecord  一对一关联的实例:

  Classroom  has one  Teacher

classroom 的属性: name,capacity,teacher

teacher 的属性:name,sex,age

利用Scaffold 生成器:

$ rails g scaffold teacher name:string sex:string age:integer

$ rails g scaffold classroom name:string capacity:integer teacher:references

Scaffold 已经为我们生成了基本的程序框架了。

然后修改app/views/classroom/_form.html.erb 的内容,添加选择老师的下拉框,并且为每个输入框添加默认值。

<%= form_for(@classroom) do |f| %>

  <% if @classroom.errors.any? %>

    <div id="error_explanation">

      <h2><%= pluralize(@classroom.errors.count, "error") %> prohibited this classroom from being saved:</h2>

 

      <ul>

      <% @classroom.errors.full_messages.each do |msg| %>

        <li><%= msg %></li>

      <% end %>

      </ul>

    </div>

  <% end %>

 

  <div class="field">

    <%= f.label :name %><br />

    <%= f.text_field :name ,{:value => "梨花教师"} %>

  </div>

  <div class="field">

    <%= f.label :capacity %><br />

    <%= f.number_field(:capacity,{:value => 20}) %>

  </div>

  <div class="field">

    <%= f.label :teacher %><br />

    <%= f.select(:teacher_id,Teacher.all.collect{|p| [p.name,p.id]},{:include_blank =>"选择老师...",:selected=>2}) %>

  </div>

  <div class="actions">

    <%= f.submit %>

  </div>

<% end %>

修改app/views/classroom/index.html.erb 的内容:

<td><%= classroom.teacher.name %></td>

即可。

访问地址 http://localhost:3000/classrooms 即可添加内容和结果了

相关推荐