Skip to main content

NoMethodError in Contacts#edit

Rails • Asked by Don Neethling
Hi all, I am new to Ruby as well as Rails
I am working my way through a treehouse course and I have hit a bit of an obstacle.

This is what my routes file looks like
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  get '/contacts/:id/edit', to: 'contacts#edit'
  get '/contacts', to: 'contacts#index', as: 'home'
  get '/contacts/new', ato: 'contacts#new', as: 'new'
  get '/contacts/:id', to: 'contacts#show', as: 'shows'
  post '/contacts', to: 'contacts#create'
end

the method in the controller is as follows
    def edit
        @contact = Contact.find(params[:id])
    end
and this is what the edit.html.erb file looks like
<%= form_for(@contact) do |c| %>
    <div>
        <%= c.label 'First Name' %>
        <%= c.text_field :fname %>
    </div>
    <div>
        <%= c.label 'Last Name' %>
        <%= c.text_field :lname %>
    </div>  
    <div>
        <%= c.label :number %>
        <%= c.text_field :number %>
    </div>  

    <div>
        <%= c.submit %>
    </div>
<% end %>

as is this will result in the following when I I try to load the edit page (example: http://localhost:3000/contacts/1/edit)


NoMethodError in Contacts#editShowing 

/Users/donovanneethling/Ruby/addressbook/app/views/contacts/edit.html.erbwhere line #1raised:

undefined method `contact_path' for #<#<Class:0x007fca54438cf0>:0x007fca57e82a78>
Did you mean?  contacts_path




However when I amend the edit route as follows
get '/contacts/:id/edit', to: 'contacts#edit', as: 'contact'
 the page loads correctly.

Would someone be able to explain this to me, I am guessing it has something to do with form_for...



Is there any specific reason you adding the routes manually instead of using `resources :contacts` (this will make sure you get all the restful urls you need)? That should definitely fix your routing problems. 
If you keep to the conventions, Rails is easier to handle and doesn't give you headaches like this.

As @jack mentioned, it's probably better using resources.  This should fix things.  If it doesn't please post your error with any potential stacktrace and the community will have a look.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 22,346+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.