Saad
Saad

Reputation: 28486

undefined method `_path' in form, with routes defined at :resources

I've been stuck on this for a bit and can't figure out the exact reason why I'm getting the following error:

undefined method `entries_path' for <%= form_for(@entry) do |f| %>

entry_controller:

class EntryController < ApplicationController
  def index
  end

  def new
    @entry = Entry.new
  end

   def create
    @entry = Entry.new(user_params)
    if @entry.save
      redirect_to @entry
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:entry).permit(:comment, :flag)
    end

end

routes has:

resources :entry

and the new page where the error occurs:

<%= form_for(@entry) do |f| %>

  <%= f.label :comment %>
  <%= f.text_field :comment %>

  <%= f.label :flag %>
  <%= f.text_field :flag %>

<% end %>

I can't figure out why I'm getting this error.

Upvotes: 1

Views: 1784

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29389

form_for needs to reference the path associated with @entry (i.e. entries_path), but your routes.rb file uses the singular form of the resource (:entry) rather than the required plural form (:entries), so the proper path names don't exist.

Rails models use the singular form, but the Rails database, controllers, views use the plural form and this is reflected in the routes file. One way to remember this is that a model is describing a single class that each object belongs to. Everything else, pretty much, is responsible for managing multiple instances, so while they themselves are singular (e.g. Controller), they refer to the objects they manage in the plural form (e.g. EntriesController, controller/entries directory).

See Ruby on Rails plural (controller) and singular (model) convention - explanation for more discussion of this.

Upvotes: 2

Meri Alvarado
Meri Alvarado

Reputation: 191

Controller and views should always be treated in plural form. For example, if you have an object Book, then the controller declaration should be

class BooksController < ApplicationController

and the views( new, edit, show, index ) should be inside a folder named

/books

Also, the declaration of routes should be in plural form. In this case, the routes should be declared as

resources :books

You could try to generate the controller and view folder by running in your terminal:

rails generate controller name_of_object_in_plural_form( for sample, books)

The script will generate a controller named books_controller.rb and /books folder under /views

Upvotes: 0

Related Questions