【发布时间】:2014-08-30 14:31:35
【问题描述】:
我有一个“一间教室有很多学生”的协会。我想创建一个表单,我可以在其中创建一个学生并为他分配一个教室。我在创建表单时遇到问题。
model/classroom.rb
class Classroom < ActiveRecord::Base
has_many :students
end
模型/学生.rb
class Student < ActiveRecord::Base
belongs_to :classroom
end
我想创建一个新学生并将其分配到某个教室。
<%= form_for(@student) do |f|%>
<%= f.label :name %>
<%= f.text_field :name %>
<br />
<br />
<%= f.label :student.classroom.number %> #Is this correct?
<%= f.text_field :student.classroom.number %> #Is this correct?
<%= f.submit %>
<%end%>
每个模型的属性是
1.9.3-p448 :026 > Classroom
=> Classroom(id: integer, number: string, created_at: datetime, updated_at: datetime)
1.9.3-p448 :027 > Student
=> Student(id: integer, name: string, created_at: datetime, updated_at: datetime, classroom_id: string)
students_controller
class StudentsController < ApplicationController
def index
@students = Student.all
end
def show
@student = Student.find(params[:id])
end
def new
@student = Student.new
end
def create
@student = Student.new(article_params)
respond_to do |format|
if @student.save
format.html {redirect_to(@student, notice: 'Student was successfully created.')}
else
format.html {render action: "new"}
end
end
end
private
def article_params
params.require(:student).permit(:name, :classroom_id)
end
end
教室控制器
class ClassroomsController < ApplicationController
def index
@classrooms = Classroom.all
end
def show
@classroom = Classroom.find(params[:id])
end
def new
@classroom = Classroom.new
end
def create
@classroom = Classroom.new(article_params)
respond_to do |format|
if @classroom.save
format.html {redirect_to(@classroom, notice: 'Classroom was successfully created.')}
else
format.html {render action: "new"}
end
end
end
private
def article_params
params.require(:classroom).permit(:number)
end
end
【问题讨论】:
-
您要将学生分配到现有教室还是新教室?
-
现有教室。 :)
-
@RailsNewbie 不,这是不正确的。使用隐藏字段发送您的教室编号或使用选择,用户可以从教室列表中选择,或者您可以在控制器方法本身中分配班级。根据您的应用设计决定您想做什么
标签: ruby-on-rails