Nikola Stojaković
Nikola Stojaković

Reputation: 2305

NoMethodError for new controller in Rails

Cities#new controller shows error involving cities_path, but I don't have it in any file nor in CitiesController. I checked all files, tried to restart the server but still nothing.

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

Routes

  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 (error is raised on first line)

<%= 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 %>

Upvotes: 0

Views: 41

Answers (1)

user229044
user229044

Reputation: 239311

When you use form_for @city, and @city is a new record, form_for will try to find a cities_path to POST the new attributes back to.

You should be using resources :cities in your routes file to automatically define the routes and their names. If you want to define a limited set of routes, you can use :only or :except:

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

If you don't use resources, you either need to explicitly specify a path for your form_for call, or you need to provide a route named cities_path manually:

post "/index" => "cities#create", as: :cities

Note that index routes don't typically actually contain the word index, you should really just be posting to /cities, not /index.

 post "/cities" => "cities#create", as: :cities

Upvotes: 1

Related Questions