无法在Rails中提交表单

时间:2016-10-03 18:57:36

标签: ruby-on-rails ruby-on-rails-4 simple-form

我有2个模型,称为讲师和请求相关联。我想提交一个属于教师的请求,但在控制台上收到以下错误。有人可以帮助我吗?谢谢,

Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"SaLDbXaZOy2cvGILrC9IJ7vInkF0xG42bf84k3IcDj+eFN9lTRfZlkGUMr8s82zQEdO9dgJ3Set935RGH8uv9w==", "request"=>{"name"=>"dsada", "email"=>"dsadas", "phone"=>"sadsadd", "message"=>"sadsa"}, "commit"=>"Create Request"}
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
No template found for RequestsController#create, rendering head :no_content
Completed 204 No Content in 38ms (ActiveRecord: 0.3ms)

申请表

    <hr>
<%= simple_form_for([@request, @instructor.requests.build], :url =>{ :controller =>"requests",
                                              :action => "create" }) do |f| %>
  <%= f.input :name, label: "Your name" %>
  <%= f.input :email %>
  <%= f.input :phone, label: "Phone number" %>
  <%= f.input :message, as: :text %>
  <br>
  <%= f.button :submit, class: "btn btn-danger" %>
<% end %>
<br>
<br>

请求控制器

    class RequestsController < ApplicationController

  def index
    if params[:search].present?
      @instructors = Instructor.near(params[:search], 50)
    else
      # Shows all listed instructors by the created date.
      @instructors = Instructor.order('created_at DESC')
    end
  end

  def show
    @instructor = Instructor.find(params[:id])
  end

  def create
    @request = Request.new(request_params)

    if @request.save
      redirect_to "root"
    end
  end

  private

  def request_params
    params.require(:request).permit(:name, :email, :phone, :message)
  end
end

2 个答案:

答案 0 :(得分:1)

如果您的请求控制器嵌套在教师之下,您可能意味着:

simple_form_for([@instructor, @instructor.requests.build], ...

这些控制器也很常见:

@instructor = Instructor.find(params[:id])
@request = @instructor.requests.new(request_params)
if @request.save
  # ...

删除其冗余的:url =>{ :controller =>"requests", :action => "create",表单构建器应该从[@request, @instructor.requests.build]

中找出它

如果@request已保存,您将重定向到root_path,但如果请求失败(似乎是这种情况),您就无法执行任何操作,这对{ {1}}在这种情况下。请参阅指南中的示例控制器:http://guides.rubyonrails.org/action_controller_overview.html#parameters

最终您可以更改此默认行为,但我建议您从基础知识开始,并在知道其工作原理后进行更改。

答案 1 :(得分:0)

您的模型无效,因此不会重定向(因为save会返回false)。所以你需要重写update动作:

def create
  @request = Request.new(request_params)

  if @request.save
    redirect_to "root"
  else
    render :new
  end
end

<强>更新

您使用Rails 5.0,因此如果您声明belongs_to,它还会为外键添加状态验证。因此,您需要以这种方式创建请求对象:

@request = Instructor.find(params[:instructor_id]).requests.build(request_params)