rails 生成器命令非常简单:
$ rails g model Student first_name:string last_name:string date_of_birth:date email:string mobile_number:string gender:string address:string city:string pin_code:string state:string country:string courses_applied_for:string
对于qualitfication 和hobbies,您必须添加单独的模型:
$ rails g model Qualitification examination:string board:string percentage:decimal year_of_passing:string student_id:integer:index
$ rails g Hobbie title:string student_id:integer:index
student 模型应如下所示:
class Student < ActiveRecord::Base
has_many :hobbies
has_many :qualifications
accepts_nested_attributes_for :hobbies
accepts_nested_attributes_for :qualifications
end
Hobbie 模型:
class Hobbie < ActiveRecord::Base
belongs_to :student
end
Qualification 模型:
class Qualification < ActiveRecord::Base
belongs_to :student
end
接下来是students_controller
class StudentsController < ApplicationController
def new
@student = Student.new
end
def create
@student = Student.new(student_params)
if @student.save
redirect_to root_path
else
render :new
end
end
private
def student_params
params.require(:student).permit(:first_name, :last_name, :date_of_birth, :email, :mobile_number, :gender, :address, :city, :pin_code, :state, :country, :courses_applied, hobbies_attributes: [:title], qualifications_attributes: [:examination, :board, :percentage, :year_passing])
end
end
最后表格应该如下所示,我将忽略学生字段,我将向您展示爱好和资格:
<%= form_for @student do |f| %>
.
.
.
<%= f.fields_for :qualifications do |qf| %>
<%= qf.text_field :examination %>
<%= qf.text_field :board %>
<%= qf.text_field :percentage %>
<%= qf.text_field :year_of_passing %>
<% end %>
<%= f.fields_for :hobbies do |qf| %>
<%= qf.text_field :title %>
<% end %>
<% end %>
如果您想动态添加更多 qualifications 或 hobbies,我建议您查看 Ryan Bates 的 nested_form gem,它将对您有很大帮助。
希望这会有所帮助!