【问题标题】:undefined local variable or method in ROR appROR 应用程序中未定义的局部变量或方法
【发布时间】:2017-08-04 00:53:03
【问题描述】:

我在 views/products/show.html.erb 中显示照片时遇到问题。我总是收到这个错误:

未定义的局部变量或方法“产品”
你的意思是? @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.rbmodel

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

我不知道为什么会出现这个错误,有人可以建议吗?

【问题讨论】:

  • 您是否使用任何 before 回调在 show 方法中设置一些变量?可以加整个控制器吗?
  • 是的@SebastiánPalma 请查看我添加的控制器,我正在使用before_action :set_product, only: [:show, :edit, :update, :destroy] 这对这有什么影响?怎么办?
  • 你想要一个 show 方法来获取所有记录吗?还是只是一个特定的?,在这种情况下,您可以删除 @products 变量,然后尝试迭代来自 set_product 方法的 @product 中的图像,例如 @product.images.each ...
  • 我想查看show.html.erb 中显示的产品的所有图片计划是使用某种Carrousel 来显示它们

标签: ruby-on-rails ruby


【解决方案1】:

使用实例变量 @product 而不是 product

product 是一个局部变量,因此在显式共享为局部变量之前不能在节目文件中使用。

【讨论】:

    【解决方案2】:

    你的 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 %>
    

    【讨论】:

    • 成功了,不知道为什么我没有弄清楚我自己:)
    猜你喜欢
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多