在rails on rails应用程序中无法在产品图像下方显示随机图像?

时间:2017-05-11 16:08:45

标签: ruby-on-rails ruby join foreign-keys

我希望能够在产品图片下方显示3个随机产品图片,到目前为止,我已将此代码插入产品图片下方,如views/products/show.html.erb

所示

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

1 个答案:

答案 0 :(得分:1)

让我们打破这个:

@products = Category.joins(:products).where(:products => {:id => @product.image})
  • @products好的,可能是Product个实例
  • 的集合
  • Category.joins(:products)嗯,这会返回Category
  • 的实例
  • where(products: { id: @product.image })等待,按ID匹配@product.image的产品进行过滤,表面上是字符串网址或文件路径

所有在一起:@products =一系列带有相关产品的类别,其中数字ID与特定产品上的特定字符串相匹配。

我对你的建议是review the Rails Guides,特别注意ActiveRecord Basics