Reputation: 1619
I keep getting a undefined method `model_name' for NilClass:Class.
In the layout file: [application.html.erb]
<section id="featured">
<%= render 'subscribers/new' %>
</section>
In the form partial: [views > subscribers > _new.html.erb]
<%= form_for @subscriber, :url => subscribe_path do |f| %> [THIS LINE PRODUCES THE ERROR]
<div class="field">
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit 'Add me to the list' %>
</div>
<% end %>
In the subscribers controller: [controllers > subscribers_controller.rb]
def new
@subscriber = Subscriber.new
end
I'm a beginner at ROR, and I've looked around StackOverflow, but can't find any answers for my specific case.
Upvotes: 0
Views: 211
Reputation: 3965
The problem is, that you are rendering the subscribers/new template directly in the layout, but only initializing a Subscriber in the subscriber controller.
You need to create a subscribers/new.html.erb file (without the leading underscore, so it is not a partial)
Somewhere in your layout file you should have a yield
call.
When you access /subscribers/new rails renders the new.html.erb template file, and stuffs it in where yield
is called in the layout.
If you really need this form on every page, you will need to initialize a new subscriber on every page. You could do this with a before filter in the application controller. But then you would not need the new action in the subscriber controller.
Upvotes: 0
Reputation: 13581
What path are you hitting when you are seeing this error?
If you are navigating to any path other than /subscribers/new
then @subscriber
will be nil
and the form will throw the error that you are seeing. You are rendering a form via a partial in your view layout, that layout is rendered (presumably) throughout the app. Thus @subsriber
won't always be set.
Upvotes: 1