想在网络浏览器的学校内创建一名教师。不确定我需要做什么代码。使用脚手架创建学校和控制器和模型来创建教师。我的目标是在创建学校后能够添加教师。
学校模式
class School < ActiveRecord::Base
has_many :teachers
end
教师模型
class Teacher < ActiveRecord::Base
belongs_to :school
end
学校管理员
class SchoolsController < ApplicationController
before_action :set_school, only: [:show, :edit, :update, :destroy]
# GET /schools
# GET /schools.json
def index
@schools = School.all
end
# GET /schools/1
# GET /schools/1.json
def show
end
# GET /schools/new
def new
@school = School.new
end
# GET /schools/1/edit
def edit
end
# POST /schools
# POST /schools.json
def create
@school = School.new(school_params)
respond_to do |format|
if @school.save
format.html { redirect_to @school, notice: 'School was successfully created.' }
format.json { render :show, status: :created, location: @school }
else
format.html { render :new }
format.json { render json: @school.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /schools/1
# PATCH/PUT /schools/1.json
def update
respond_to do |format|
if @school.update(school_params)
format.html { redirect_to @school, notice: 'School was successfully updated.' }
format.json { render :show, status: :ok, location: @school }
else
format.html { render :edit }
format.json { render json: @school.errors, status: :unprocessable_entity }
end
end
end
# DELETE /schools/1
# DELETE /schools/1.json
def destroy
@school.destroy
respond_to do |format|
format.html { redirect_to schools_url, notice: 'School was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_school
@school = School.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def school_params
params.require(:school).permit(:name)
end
end
教师控制器
class TeachersController < ApplicationController
end
学校/视图/显示
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= @school.name %>
</p>
<%= link_to 'Edit', edit_school_path(@school) %> |
<%= link_to 'Back', schools_path %>
答案 0 :(得分:0)
您可以在您的学校或教师控制器中执行此操作,您可能需要创建,绝对更新。假设学校控制员和那个参数包括教师姓名:teacher_name。
def update
@school.teachers = Teacher.new(school_params[:teacher_name])
respond_to do |format|
... snip for brevity ...
end
end
我假设您的数据库表已经使用[迁移]设置。1
答案 1 :(得分:0)
从教师那边:
在教师新页面(您的表单)中,您需要有一个教师可以拥有的学校的选择框,这些学校将其ID作为值(来自数据库)。教师模型将school_id作为其属性之一,一旦你进入rails控制台并键入类似School.first.teachers的内容,你将获得该学校所有教师的列表。