I have been working on a project based on Michael Hartl's book Ruby on
Rails Tutorial in order to try to teach myself Ruby on Rails. However,
when it tries to render a form designed to allow a user to submit a
small message, I get an error saying, "undefined method `model_name' for
NilClass:Class". It says the error is at line 1, which is "<%= form_for
@micropost do |f| %>". I have the following defined in
app/controllers/microposts_controller.rb:
def new
@micropost = Micropost.new
end
I would have expected this code to create a blank Micropost object that
gets passed to form_for, but that doesn't seem to be what happened. I
attached a few files for reference.
Thank you for the help. Putting "@micropost = Micropost.new" in
pages_controller.rb solved this error. However, I now have a new error
which states "undefined method `humanize' for nil:NilClass". It says the
error is at the line "<%= f.label @user.email %><br />". I defined @user
= User.new in pages_controller.rb.
I am doing this a little bit differently from Michael Hartl's book. I
want to be able to submit on one form the micropost content, user e-mail
address and password instead of having the user logged in.
Sam Serpoosh wrote in post #1069239:
when you want to create a blank instance of a model for a form's sake
like
this
scenario, you should create that blank instance in the controller's
action
which
leads to that specific view you're rendering the form in.
As I recall in Michael Hartl's Ruby on Rails Tutorial sample application
you
rendered the _micropost_form partial in the Page's controller
home.html.erb
view which means you'll go to that view through the home action in the
PagesController and for handling this nil problem you should put that
line of code (@micropost = Micropost.new) in the home action of the
pages controller.