【问题标题】:ActionController::RoutingError: No route matches [POST] "/locations/new"ActionController::RoutingError: 没有路由匹配 [POST] "/locations/new"
【发布时间】:2014-01-10 20:18:40
【问题描述】:

路线

resources :locations, :only => [:new, :create]

控制器

 class LocationsController < ApplicationController
  def new
    @location = Location.new
  end

  def create
    @location = Location.new(location_params)

    if @location.save
      flash[:notice] = 'Created location successfully'
      redirect_to new_location_path
    else
      flash[:notice] = 'Invalid information. Please try again'
      render :new
    end
  end

  private

  def location_params
    params.require(:location).permit(:name, :street, :city, :state)
  end
end

点击保存时出现错误信息。

 ActionController::RoutingError:
       No route matches [POST] "/locations/new"

查看

<%= simple_form_for :locations do |form| %>
  <%= form.input :name %>
  <%= form.input :street %>
  <%= form.input :city %>
  <%= form.input :state %>

  <%= form.submit 'Create location' %>
<% end %>

使用 capybara 进行测试,当我点击保存时,它会创建一个新位置。我不太确定为什么它不知道发布路线是什么,因为我有新的和创建的路线。如果我将 binding.pry 放在 create 方法的正下方,它就不会被调用。所以我的 create 方法由于某种原因没有被调用。

编辑:

耙子路线

locations    POST   /locations(.:format)                        locations#
new_location GET    /locations/new(.:format)                    locations#new

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    资源通常 GET 到 new 并 POST 到 create。因此,您的表单可能正在提交回新操作,而不是提交到创建操作。

    这里是这个指南:http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

    【讨论】:

      【解决方案2】:

      问题出在视图中。

      <%= simple_form_for :locations do |form| %>
        <%= form.input :name %>
        <%= form.input :street %>
        <%= form.input :city %>
        <%= form.input :state %>
      
        <%= form.submit 'Create location' %>
      <% end %>
      

      当我应该从控制器调用实例变量 @location 时,我调用了位置符号。

      实际问题是 rails 3.2.12 不接受私有参数

      【讨论】:

      • 网上好像有很多例子代码中form_for之类的和符号一起使用。
      【解决方案3】:

      使用resources,应使用GET 而不是POST 获取new 操作。 create 将是 POST。检查你的rake routes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 2015-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多