Ruby on Rail 4 App中的随机图像

时间:2017-09-29 14:12:34

标签: ruby-on-rails ruby loops random

我正在使用此代码显示所选产品所属类别产品的随机图片。

 <div class="row container product-teaser">
   <h4 class="text-center teaser-text"> similar products to <%= @product.title %> : </h4>

     <% @products_rand.each do |product| %>
       <div class="col-sm-2 col-xs-3 center-block product-thumbs-product-view" >
          <%= link_to product_path (product) do %>
             <% if product.images.first %>
          <%= image_tag @product.images.first.image.url(:medium), :size => "100%x100%", class: "img-responsive center-block" %>
          <% end %>        
      <% end %>
      <h5 class="text-center"><%= link_to product.title, product, class: "text-center" %></h5>
  </div>
    <% end %>
 </div>

问题是此loop中的产品都显示所选产品的图像,但产品的名称和链接是正确的。

图片显示了我的意思,客户选择了一款名为ATLAS的产品和类似产品(来自同一category的产品)正在显示Atlas图片。

enter image description here

这是product_controller.rb

 class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]


  def show

  offset = rand(100)
  @meta_title = "Concept Store #{@product.title}"
  @meta_description = @product.description
  @products_rand = Product.where(category_id: @product.category_id).order("RANDOM()").limit(6)
 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, :image, :category_id, :stock_quantity, :label_id, :query, :slug, images_attributes: [:image , :id , :_destroy])
end


end

1 个答案:

答案 0 :(得分:1)

此:

<%= image_tag @product.images.first.image.url(:medium), :size => "100%x100%", class: "img-responsive center-block" %>

应该是:

<%= image_tag product.images.first.image.url(:medium), :size => "100%x100%", class: "img-responsive center-block" %>

如果您使用@product,则表示您正在从控制器引用该实例。如果您使用product,则表示您正在引用每个循环中的实例。