undefined method `default_image' for nil:NilClass

ActionView::Template::Error (undefined method `default_image' for nil:NilClass):
    409:
    410: <!-- Image -->
    411: <div class="image">
    412:   <% if @product.default_image %>
    413:
    414:     <a href="" class="main"><%= image_tag @product.default_image.path, :weight => '262px',:height => '197px'%></a>
    415:   <% end %>

model:

 Return attachment for the default_image role

 @return [String]
def default_image
  self.attachments.for("default_image")
end

 Set attachment for the default_image role
def default_image_file=(file)
  self.attachments.build(file: file, role: 'default_image')
end

controller:

class ProductsController < ApplicationController
  def index
    @products = Shoppe::Product.root.ordered.includes(:product_categories, :variants)
    @products = @products.group_by(&:product_category)
    @product = Shoppe::Product.root.find_by_permalink(params[:permalink])
    @order = Shoppe::Order.find(current_order.id)
  end
end


ANSWERS:


@product = Shoppe::Product.root.find_by_permalink(params[:permalink]) returns nil. So when you try to call default_image on it then it breaks.

You could check it exists via

<% if @product && @product.default_image %>
  <a href="" class="main"><%= image_tag @product.default_image.path, :weight => '262px',:height => '197px'%></a>
<% end %>

Or if you wanted to raise an error if it doesn't exist you can use the bang method of the dynamic finder.

@product = Shoppe::Product.root.find_by_permalink!(params[:permalink])

Also that's the older syntax for dynamic finders. The new one is

@product = Shoppe::Product.root.find_by!(permalink: params[:permalink])


 MORE:


 ? C# WinForms - Determine when void method returns
 ? C# - Unable to add item to listview from method invoked from class
 ? GCC : Return statement from a void function in C
 ? How to call objective c method from c method iOS
 ? Creating multiple choice for user
 ? Does "return;" at the end of a void method in Java have ANY impact on performance?
 ? Java If else nested. public static void ()
 ? FETCH API return undefined
 ? PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"
 ? Undefined Index PHP, MySQL, PhpMyAdmin