2017-08-04 20 views
1

我在顯示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.rbshow方法它是在我添加了@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 

我不知道爲什麼我收到此錯誤,可有人請指教?

+0

你使用任何回調之前設置show方法中的一些變量?你可以添加整個控制器嗎? –

+0

是@SebastiánPalma請參閱我添加的控制器,我正在使用'before_action:set_product,只有:[:show,:edit,:update,:destroy]'這是如何影響這個的?該怎麼辦? – Slowboy

+0

你想要一個show方法來獲取所有記錄?或者只是一個特定的?,在這種情況下,您可以刪除@ @ products'變量,然後嘗試迭代來自'set_product'方法的'@ product'的圖像,例如'@product.images.each。 ..' –

回答

1

你的show方法中有兩個不同的變量,但你沒有使用它們中的任何一個,因爲你在做product.images,這意味着某個地方的局部變量,如果你想從特定記錄中獲取圖像,您可以使用在您的私人方法set_product中設置的@product變量,如果您不需要,可以刪除@products = Product.all

嘗試的東西,如:

<% @product.images.each do |image_product| %> 
    <%= image_tag image_product.image.url(:medium), class: "img-responsive" %> 
<% end %> 
+0

,它們做了詭計,不知道爲什麼我沒有弄清楚我的自我:) – Slowboy

2

使用實例變量@product的替代產品

產品是一個局部變量,因此不能在演示文件中使用,直到明確作爲局部變量共享。

相關問題