Rails中新控制器的NoMethodError

时间:2016-10-13 18:58:41

标签: ruby-on-rails

城市#new 控制器显示涉及 cities_path 的错误,但我没有在任何文件或 CitiesController 中。我检查了所有文件,试图重启服务器,但仍然没有。

undefined method `cities_path' for #<#<Class:0x007f9e4c1cb348>:0x00000003836140>
Did you mean?  city_path

CitiesController

class CitiesController < ApplicationController

    def index
        @cities = City.all
    end

    def show
        find_city
    end

    def new
        @city = City.new
    end

    def edit
        find_city
    end

    def update
        find_city

        if @city.save
            redirect_to city_path(@city)
        else
            render "edit"
        end
    end

    def create
        @city = City.new(city_params)

        if @city.save
            redirect_to index_path
        else
            render "new"
        end
    end

    private

    def find_city
        @city = City.find(params[:id])
    end

    def city_params
        params.require(:city).permit(:name, :icon_url)
    end

end

路线

  get "/cities/new" =>  "cities#new", as: "new_city"
  post "/index" => "cities#create"
  get "/cities/:id" => "cities#show", as: "city"
  get "/cities/:id/edit" => "cities#edit", as: "edit_city"
  patch "/city/:id" => "cities#update"

表单(第一行引发错误)

<%= form_for @city do |f| %>

    <% if @city.errors.any? %>
        <div class="errors">
            <ul>
                <% city.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                <% end %>
            </ul>
        </div>
    <% end %>

    <%= f.label "Name:" %>
    <%= f.text_field :name, class: "form-control" %>

    <%= f.label "Icon:" %>
    <%= f.text_field :icon_url, class: "form-control" %>

    <%= f.submit "Pošalji" %>

<% end %>

1 个答案:

答案 0 :(得分:1)

当您使用form_for @city,并且@city是新记录时,form_for会尝试找到cities_path以将新属性发回。

您应该在路线文件中使用resources :cities来自动定义路线的名称。如果您要定义一组有限的路线,可以使用:only:except

resources :cities, only: %i(new create show edit update)

如果您不使用resources,则需要明确指定form_for电话的路径,,您需要提供名为{的路线{1}}手动:

cities_path

请注意,索引路径通常实际上不包含单词post "/index" => "cities#create", as: :cities ,您应该真正发布到index,而不是/cities

/index