我有一个教室有很多学生的协会。我想创建一个表格,我可以在其中创建一个学生并为他分配教室。我在创建表格时遇到了问题。
型号/classroom.rb
class Classroom < ActiveRecord::Base
has_many :students
end
模型/student.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
如果您已经知道要将教室添加到哪个教室,则可以设置一个隐藏字段,将其设置为教室本身:
<%= f.hidden_field, :classroom_id, value: here_you_put_the_classroom_id $>
并且不要忘记在控制器的允许参数中添加:classroom_id。
如果希望选择要放置学生的教室,则可以采用另一种方法,可以创建一个通过所有教室的选择字段。
<% classroom_array = Classroom.all.map { |classroom| [classroom.name, classroom.id] } %>
<%= options_for_select(classroom_array) %>
不要忘记再次添加允许的参数。希望能帮助到你。
***更新***
options_for_select应该放在de select标记内,如下所示:
<% classroom_array = Classroom.all.map { |classroom| [classroom.number, classroom.id] } %>
<%= f.label :classroom %>
<%= f.select(:classroom_id, options_for_select(classroom_array)) %>
***更新2 ***
只要您将教室ID作为参数传递,也可以选择Pluck。因此,代码可以重构为:
<%= f.label :classroom %>
<%= f.select :classroom_id, Classroom.all.pluck(:name, :id) %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句