nil:NilClass 的未定义方法“default_image”
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 %>
型号:
# 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
控制器:
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
@product = Shoppe::Product.root.find_by_permalink(params[:permalink])
returns 无。因此,当您尝试对其调用 default_image
时,它就会中断。
您可以通过
检查它是否存在
<% if @product && @product.default_image %>
<a href="#" class="main"><%= image_tag @product.default_image.path, :weight => '262px',:height => '197px'%></a>
<% end %>
或者如果你想在错误不存在时引发错误,你可以使用动态查找器的 bang 方法。
@product = Shoppe::Product.root.find_by_permalink!(params[:permalink])
这也是动态查找器的旧语法。新的是
@product = Shoppe::Product.root.find_by!(permalink: params[:permalink])
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 %>
型号:
# 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
控制器:
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
@product = Shoppe::Product.root.find_by_permalink(params[:permalink])
returns 无。因此,当您尝试对其调用 default_image
时,它就会中断。
您可以通过
检查它是否存在<% if @product && @product.default_image %>
<a href="#" class="main"><%= image_tag @product.default_image.path, :weight => '262px',:height => '197px'%></a>
<% end %>
或者如果你想在错误不存在时引发错误,你可以使用动态查找器的 bang 方法。
@product = Shoppe::Product.root.find_by_permalink!(params[:permalink])
这也是动态查找器的旧语法。新的是
@product = Shoppe::Product.root.find_by!(permalink: params[:permalink])