Undefined method 'model_name' for NilClass: Class

The browser returned me the following error in Locals # show:

undefined method 'model_name' for NilClass: Class

51: <%= form_for(@food) do |f| %> 52: <%= render 'shared/error_messages', object: f.object %> 53: <div class="field"> 54: <%= f.label :nome %> 

Here is my locals_controller.rb (show action)

  def show @local = Local.find(params[:id]) @foods = @local.foods.paginate(page: params[:page]) respond_to do |format| format.html # show.html.erb format.json { render json: @local } end 

end

And here food_controller.rb (create action)

 def create @food = @local.foods.build(params[:food]) if @food.save flash[:success] = "Food created!" redirect_to '/locals' else flash[:error] = "Error on creating food" render '/locals' end end 

The product model and local model are associated with: has_many and belongs_to

What is the problem? Thanks you

+4
source share
4 answers

Then change your view code as:

 <%= form_for :food, :url => {:action => :create} do |f| %> 
+8
source

Check by adding the following code (I assumed your model is local)
@food = Local.new
In a new action

+2
source

If this happens when you EDIT, but it works while you CREATE

You must add before the action and set the food

  before_action :set_food, only: [:show, :edit, :update, :destroy] 
0
source

You can use any of the following codes:

 <%= form_for :food, :url => {:controller => :food, :action => :create} do |f| %> <%= form_for :food, url: food_create_path do |f| %> <%= form_for Food.new , url: food_create_path do |f| %> 
0
source

All Articles