2017-05-11 33 views
0

我希望能夠表現出以下產品形象3張隨機的產品圖片,到目前爲止,我所插入的產品圖像下面這段代碼作爲views/products/show.html.erb無法在Ruby on rails應用程序中的產品圖像下方顯示隨機圖像?

views/products/show.html.erb

<div class="col-xs-12 col-sm-6 center-block" > 

    <%= image_tag @product.image.url(:medium), class: "img-responsive" %> 
    #This is the Product image# 
    ##EDITED ## 
    #Below is the codesnippet for three products to appear## 
    <% @products.each do |product| %> 
    <div class="col-sm-2 center-block " > 

<%= link_to product_path (product) do %> 
      <%= image_tag product.image.url(:thumb), class: "img-responsive" %> 
     <% end %> 

    <div class="product_description"> 

     <h5><%= link_to product.title, product %></h5> 
    </div> 
    </div> 
<% end %> 

而且在看到我的products_controller.rb我有代碼,我相信問題是在@products中找到的,但我不確定它是什麼。請有人建議我。

products_controller.rb

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


    def show 
    @meta_title = "Concept Store #{@product.title}" 
    @meta_description = @product.description 
    @products = Product.all ###EDITED### 
    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, :price_isl, :image, :category_id, :stock_quantity, :label_id, :query, :slug) 
    end 
end 

我的模型ProductsCategories有關係

product.rb

class Product < ActiveRecord::Base 
belongs_to :category 
belongs_to :label 

has_many :product_items, :dependent => :destroy 

extend FriendlyId 
friendly_id :title, use: [:slugged, :finders] 

    validates :title, :description, presence: true 
    validates :price_usd, :price_isl, numericality: {greater_than_or_equal_to: 0.01} 
    validates :title, uniqueness: true 

has_attached_file :image, styles: { medium: "500x500#", thumb: "100x100#" } 
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ 
end 

category.rb

class Category < ActiveRecord::Base 

has_many :products, :dependent => :nullify 

extend FriendlyId 
friendly_id :name, use: [:slugged, :finders] 
end 
+0

我不認爲'each_slice'會做你的想法。 [查看文檔](https://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-each_slice)。 – coreyward

回答

1

讓我們打破這:Product實例的

@products = Category.joins(:products).where(:products => {:id => @product.image}) 
  • @products沒關係,想必集合
  • Category.joins(:products)唔,這個返回的Category
  • where(products: { id: @product.image })等待,過濾器的實例通過產品的ID匹配@product.image ,這表面上是一個字符串的URL或文件路徑

全部在一起:@products =具有相關產品的類別數組,其中數字ID與特定產品上的特定字符串匹配。

我的建議你將review the Rails Guides尤其要注意的ActiveRecord Basics

+0

謝謝,我很複雜的事情。我結束了只是做'@products = Product.all'仍然我要弄清楚如何使隨機出現3圖像 – Slowboy

+1

http://stackoverflow.com/questions/2752231/random-record-in-activerecord – coreyward