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 即可添加内容和结果了
相关推荐
wl00 2020-10-28
EricNet 2020-07-05
EricNet 2020-05-27
何志文 2020-05-11
JOO 2020-04-26
happyfreeangel 2020-04-09
Poisedflw 2020-03-23
yangliuhbhd 2020-03-06
Ben的程序员生涯 2013-06-01
chenshuixian 2013-06-01
wes0 2014-05-31
mrice00 2019-12-20
EricNet 2019-12-11
89304896 2019-12-08
lihaoningxia 2013-07-09
userguanguan 2015-03-16