Search code examples
ruby-on-railsrubypartial

undefined method for nil class when rendering partial


I'm trying to run this code and it returns me

undefined method `image' for nil:NilClass

But the syntax and the code seems to be good.

index :

 - @recipes.each_slice(4) do |recipes|
  .row
    - recipes.each do |recipe|
      .col-md-3
         %h4.modal-title= recipe.title
         .modal-body
            = render :partial =>'show', :locals => {:recipe => @recipe}

_show:

.main_content
  #recipe_top.row
    .col-md-4
      = image_tag @recipe.image.url(:medium), class:"recipe_image"

Solution

  • Change your code to:

    = render :partial =>'show', :locals => { :recipe => recipe }
    

    Since you don't have a instance variable @recipe, but a local variable recipe defined in the line recipes.each do |recipe|.