I have an association of One Classroom has Many Students. I want to create a form where I can create a student and assign him a classroom. And I am having problems creating the form.
model/classroom.rb
class Classroom < ActiveRecord::Base
has_many :students
end
model/student.rb
class Student < ActiveRecord::Base
belongs_to :classroom
end
I want to create a new student and assign it to a certain classroom.
<%= 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%>
The attributes for each model are
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
classroom_controller
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