我在顯示views/products/show.html.erb
中的照片時遇到問題。我總是得到這個錯誤:未定義的局部變量或ROR應用程序中的方法
undefined local variable or method 'product' for <#:0x007fe0bc949fb8>
Did you mean?@product
這是我用來顯示視圖照片代碼:
views/products/show.html.erb
<div class="col-xs-12 col-sm-6 center-block" >
<% product.images.each do |image_product| %>
<%= image_tag image_product.image.url(:medium), class: "img-responsive" %>
<% end %>
</div>
這裏是爲products_controller.rb
爲show
方法它是在我添加了@products
後,我有錯誤信息。
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def show
@products = Product.all
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:title, :description, :price_usd, :image, :category_id, :stock_quantity, :label_id, :query, :slug, images_attributes: [:image , :id , :_destroy])
end
end
這裏是product.rb
模型
class Product < ActiveRecord::Base
acts_as_list :scope => [:category, :label]
belongs_to :category
belongs_to :label
has_many :images
accepts_nested_attributes_for :images
has_many :product_items, :dependent => :destroy
end
這裏是image.rb
模型
class Image < ActiveRecord::Base
belongs_to :product
has_attached_file :image, styles: { medium: "500x500#", thumb: "100x100#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
我不知道爲什麼我收到此錯誤,可有人請指教?
你使用任何回調之前設置show方法中的一些變量?你可以添加整個控制器嗎? –
是@SebastiánPalma請參閱我添加的控制器,我正在使用'before_action:set_product,只有:[:show,:edit,:update,:destroy]'這是如何影響這個的?該怎麼辦? – Slowboy
你想要一個show方法來獲取所有記錄?或者只是一個特定的?,在這種情況下,您可以刪除@ @ products'變量,然後嘗試迭代來自'set_product'方法的'@ product'的圖像,例如'@product.images.each。 ..' –