简体   繁体   中英

How can I create a form without using resources (action :new, :create) in Rails?

This is my controller

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

This is my views/schools/teacher.html.erb

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

I am new to Ruby on Rails, and not sure how to proceed.

You should move this to a TeachersController let me show you how:

First you need to create the controller, you can get this done by typing this on the terminal at the project root directory:

$ rails g controller teachers new

Then into your route file ( config/routes.rb ):

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

After that go to the teachers_controller.rb file and add the following:

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

Then you can have the form at views/teachers/new.html.erb :

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

Please let me know how it goes!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM