Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Why do I still get the model_name error when locals present?


I'm trying to render my dog form in another view in my PetsController.index:

def index
  @page_title = "Add Pets"
  @title = "Add Pets"
end

But I get the error:

NoMethodError in Pets#index

Showing C:/testapp/app/views/dogs/_form.html.erb where line #1 raised:

undefined method `model_name' for NilClass:Class

1: <%= form_for @dog do |f| %>

pets/index.html.erb

<div class="tab-pane" id="tab4">
   <%= render "global/flash_message" %>
   <%= render :partial => "dogs/form", :locals => {:dog => @dog } %>
</div>

I know I can do:

def index
  @page_title = "Add Pets"
  @title = "Add Pets"
  @dog = Dog.new
end

But what's the point of the local then? What's missing so I can use it from the DogsController instead?

Thanks!


Solution

  • If @dog is not assigned in your #index action, then you're assigning nil to your dog local in the call to render :partial. You could leave the instance assignment out of the action and do it in your index view (i.e. :locals => {:dog => Dog.new}, but it has to happen somewhere.