【问题标题】:Not able to display random images below product image in Ruby on rails app?无法在 Ruby on rails 应用程序中的产品图像下方显示随机图像?
【发布时间】:2017-10-10 18:20:51
【问题描述】:

我希望能够在产品图片下方显示 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

【问题讨论】:

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


【解决方案1】:

让我们分解一下:

@products = Category.joins(:products).where(:products => {:id => @product.image})
  • @products 好吧,大概是Product 实例的集合
  • Category.joins(:products) 呃,这会返回 Category 的实例
  • where(products: { id: @product.image }) 等等,按 ID 匹配 @product.image 的产品过滤,表面上是字符串 url 或文件路径

总而言之:@products = 包含相关产品的类别数组,其中数字 ID 与特定产品上的特定字符串匹配。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-09-09
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2020-01-26
  • 2014-09-02
  • 2014-03-03
相关资源
最近更新 更多