如何在Rails中不使用资源(action:new,:create)创建表单?

时间:2017-08-03 11:48:42

标签: ruby-on-rails ruby

这是我的控制器

class SchoolsController < ApplicationController
  def teacher
    @teacher = Teacher.new
  end

  def form_create
    @teacher = Teacher.new(teacher_params)
    if teacher.save
      redirect_to schools_teacher_path
    else
      flash[:notice] = "error"
    end
  end

  private
  def teacher_params
    params.require(:teacher).permit(:name)
  end
end

这是我的观点/ schools / teacher.html.erb

<%= form_for :teacher do |f| %>
  <%= f.text_field :name %> 
  <%= f.submit %>
<% end %>

我是Ruby on Rails的新手,不知道如何继续。

1 个答案:

答案 0 :(得分:1)

你应该把它移到TeachersController让我告诉你如何:

首先,您需要创建控制器,您可以通过在项目根目录的终端上键入它来完成此操作:

$ rails g controller teachers new

然后进入你的路线档案(config/routes.rb):

resources :teachers, only: [:new, :create]

之后转到teachers_controller.rb文件并添加以下内容:

class TeachersController < ApplicationController
  def new
   @teacher = Teacher.new
  end

  def reate
   @teacher = Teacher.new(teacher_params)
   if @teacher.save
    redirect_to schools_teacher_path
   else
    redirect_to schools_teacher_path, notice: "error"
  end
end

 private

 def teacher_params
  params.require(:teacher).permit(:name)
 end
end

然后您可以在views/teachers/new.html.erb

处填写表单
<%= form_for :teacher do |f| %>
 <%= f.text_field :name %> 
 <%= f.submit %>
<% end %>

请告诉我它是怎么回事!