2017-09-29 8 views
3

は私が選択した製品の中にある同じカテゴリで同様の製品のためのランダムな画像を表示するには、このコードを使用しています。ランダムイメージのApp

<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中の製品であるということです選択された1つの製品のイメージが表示されますが、製品の名前とリンクは正しく表示されます。

この写真は、ATLASと呼ばれる製品を選択し、同様の製品(同じ製品はcategory)がアトラスの画像で表示されていることを示しています。ここ

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

です:

<%= 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を使用する場合は、各ループからインスタンスを参照しています。

関連する問題