I have a form that i want to appear at the top of every page so i've included it in the /app/views/layouts/application.html.erb file and i get the error undefined method
model_name' for NilClass:Class` when trying to load the page.
Here's the form snippet in application.html.erb
<%= form_for @user do |f| %>
<h3>Add new contact</h3>
<%= f.text_field :first_name %><br />
<%= f.text_field :last_name %>
<%= f.text_field :email %>
<hr />
<%= f.submit "Add Contact" %>
<% end %>
Here's my /app/controllers/user_controller.rb
class UserController < ApplicationController
def index
end
def new
@user = User.new
end
end
I'm thinking that i'm hitting this error because since the form is in the application.html.erb file, i need to somehow specify the path, but then again i'm very new to rails.
Let me know if you need anything else posted.
EDIT Following Ola's suggestion, In my app/views/layouts/application.html.erb file I have something like this:
<div>
<%= yield :add_user %>
</div>
and in my app/views/users/new.html.erb file I have this
<% content_for :add_user do %>
<%= form_for @user do |f| %>
<h3>Add new contact</h3>
First Name<br />
<%= f.text_field :first_name %><br />
Last Name<br />
<%= f.text_field :last_name %><br />
Email<br />
<%= f.text_field :email %>
<hr />
<%= f.submit "Add Contact" %>
<% end %>
<% end %>
The form is not rendered because my url is http://localhost:3000/admin/index
and so it's looking for the add_user
content_for in app/views/admin/index.html.erb
/users
– David J.http://localhost:3000/admin/index
– Catfish/users/new
should work (kind of), though you've got your view structure all wrong - see my answer below. – Ola Tuvessonyield
directive upside down too - trust me I know how confusing all this stuff is when you first hit the rails. <%= yield :something %> will render output from the current action, which would vary depending on what page you're on. Great for when you want each controller/action to set the contents of some universal page element (often used to set the document title) but you actually want the complete opposite - to render some component the same on every page. For this you should use<%= render :partial => "thing/partial" %>
in your template. – Ola Tuvesson