我是ROR的新手。我正在使用Rails-4和Ruby 1.9.3。我想将所有学生记录插入数据库。请帮忙写出实际的格式。我有一个名为“Student”的表,其中包含以下字段
1)FIRST NAME.
2)LAST NAME.
3)DATE OF BIRTH(format-dd-mm-yy,select from option).
4)EMAIL ID.
5)MOBILE NUMBER
6)GENDER.(select from radio button value)
7)ADDRESS
8)CITY
9)PIN CODE
10)STATE
11)COUNTRY
12)HOBBIES (It takes from check box value)
13)QUALIFICATION.
format:
sl no Examination Board Percentage Year of Passing
1 Class X - - -
2 Class XI - - -
14)COURSES APPLIED FOR(takes fron radio button select value)
我想运行命令rails g model Student FIRST NAME:string etc
。以给定格式或任何其他最简单的方式插入所有字段的正确命令是什么,请与我分享。
如果我的方法在提交后位于控制器页面内,请分享一些代码片段以检索控制器页面的所有值。
def create
end
答案 0 :(得分:0)
rails generator命令非常简单:
$ 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 %>
如果您想以dinamycally方式添加更多qualifications
或hobbies
我建议您查看Ryan Bates的nested_form gem,它会对您有所帮助。
希望这有帮助!