【发布时间】: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.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.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