ruby-on-railsroutescontact-formnomethoderrormail-form

Ruby on Rails: Cannot Move URL for Contact Form Without Getting NoMethodError


I am new to rails and I am having trouble moving a contact form from "/contacts" to "/contact". Simple, I know!

I followed the following guide, and got everything working: https://rubyonrailshelp.wordpress.com/2014/01/08/rails-4-simple-form-and-mail-form-to-make-contact-form/

However, I cannot seem to do something as simple as change the URL without getting an error. As I'm learning, this seemed like something I should be able to do... I made the following changes:

1) Changed routes.rb:

match '/contacts', to: 'contacts#new', via: 'get'
resources "contacts", only: [:new, :create]

Became

match '/contact', to: 'contact#new', via: 'get'
resources "contact", only: [:new, :create]

2) Renamed "app/controllers/contacts_controller.rb" to "app/controllers/contact_controller.rb"

3) Updated and changed the first line of "contact_controller.rb":

class ContactsController < ApplicationController 

Became

class ContactController < ApplicationController

4) Moved the views from "app/views/contacts/" to "app/views/contact/"

I get the following error:

NoMethodError in Contact#new
undefined method `contacts_path' for #<#<Class:0xa0e4500>:0xa0efb28>
Did you mean?  contact_path

Thinking there is a "contacts_path" somewhere, I did a search in the entire project and no "contacts" exists.

Any help would be greatly appreciated! Thank you!

Ruby 2.3.3 Rails 5.0.1


Solution

  • The problem is that the default path for a form_for @object when the object is not persisted (new record) is always objects_path. You'll have to explicitly state the url, something like...

    <%= simple_form_for @contact, as: :contact, url: '/contact', html: { class: "new_contact", id: "new_contact" } do |f| %>
    

    BUT this is going to mess up the form for your existing contacts when you try to edit them.

    You'll have to do an <% if @contact.new_record? %> and <% else %> and <% end %> to handle the two different URLs required.

    So the best recommendation is really follow the convention! Use plurals for the controller, set the route back to the way it was.

    Unless you have a compelling reason to violate the "convention over configuration" rule, you shouldn't.

    The docs explain the default URLs used. https://apidock.com/rails/ActionView/Helpers/FormHelper/form_for