Thank you in advance for any help provided. I've tried researching this a bunch but I can't get it to work.
When trying to render contacts/_new.html.erb inside of pages/home.html.erb I get "First argument in form cannot contain nil or be empty"
I think it has something to do with which controller Rails is looking in. Does Rails know to look in my ContactsController even though the main view is coming from the PagesController? I have tried many things and researched this a lot. I've tried locals and changing url and actions. It works when it is not in a partial. It works when I hard code form_for Contact.new.
Thanks again!
_new.html.erb
<%= form_for @contact do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :comments %>
<%= f.text_area :comments, class: 'form-control' %>
</div>
<%= f.submit 'Submit',class: 'btn btn-default' %>
<% end %>
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params)
if @contact.save
redirect_to root_path, notice: "Message sent."
else
redirect_to root_path, notice: "Error occured."
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :comments)
end
end
Render with:
<%= render new_contact_path %>
in the views/pages/home.html.erb
This is because @contact
doesn't exist in your pages_controller.rb
, and at the moment to load the contact variable in your form_for
it throws this error.
You only have it defined in your contacts_controller
but that's not being accessed when you load the pages/home
view, it'll go to look for a @contact
variable defined in your pages_controller
specifically in your home
method.
Try adding it in your pages_controller.rb
as:
# app/controllers/pages_controller
def home
@contact = Contact.new
end