Reputation: 187
I've been trying to setup a contact form but I keep getting errors and I just can't figure out what I'm doing wrong. The latest error I'm getting is:
NameError in Contacts#new
Showing .../app/views/contacts/new.html.erb where line #2 raised:
undefined local variable or method `contact' for #<#<Class:0x007fa2933ca1f8>:0x007fa29a4df460>
Did you mean? @contact
concat
Extracted source (around line #2):
1
2
3
4
5
6
<h1>Contact us</h1>
<%= form_for(contact) do |f| %>
<div class="field entry_box">
<%= f.label :name %>
<%= f.text_field :name, class: "form-control entry_field" %>
</div>
My ContactsController
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params)
if @contact.save
redirect_to contacts_path, notice: "Thanks for contacting us!"
else
render :new
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :message)
end
end
Model
class Contact < ApplicationRecord
end
Routes (relevant parts)
resources :contacts, only: [:new, :create]
get "contact" =>'contacts#new'
post "contact" =>'contacts#create'
View (new.html.erb)
<h1>Contact us</h1>
<%= form_for(contact) do |f| %>
<div class="field entry_box">
<%= f.label :name %>
<%= f.text_field :name, class: "form-control entry_field" %>
</div>
<div class="field entry_box">
<%= f.label :email %>
<%= f.number_field :email, class: "form-control entry_field" %>
</div>
<div class="field entry_box">
<%= f.label :message %>
<%= f.text_field :message, class: "form-control entry_field" %>
</div>
<div class="actions center space_big">
<%= f.submit "Submit", class: "btn btn-lg btn-success" %>
</div>
<% end %>
Thanks for any assistance!
Upvotes: 0
Views: 1514
Reputation: 223
You have to write instance variable in new form just write
<%= form_for(@contact) do |f| %>
<% end %>
Upvotes: 0
Reputation: 5712
Your controller defines an instance variable, @contact
, but your view uses contact
. There's a difference - make sure your form_for
call uses the @contact
variable that your controller defines.
You have:
<%= form_for(contact) do |f| %>
which you should change to
<%= form_for(@contact) do |f| %>
because of this line in your controller
@contact = Contact.new
In most errors, Rails will give you the source code and line number that caused the exception, and will then give you a hint - in this case, it says "did you mean @contact
?"
Upvotes: 1
Reputation: 11915
The variable contact
is undefined
in new.html.erb
. See the suggestion made by rails to use @contact
?
The line
<%= form_for(contact) do |f| %>
should be
<%= form_for(@contact) do |f| %>
The instance variable @contact
is passed on to the view from the new
action of ContactsController
.
Upvotes: 1