【问题标题】:Displaying random products in ruby on rails app在 ruby​​ on rails 应用程序中显示随机产品
【发布时间】:2017-05-22 01:16:11
【问题描述】:

在我正在构建的应用程序中,客户选择了一种产品,在products/show.html.erb 中,他应该能够在下面的 div 中看到相关产品。

category.rb 和 product.rb 相关:

cateory.rb has_many :products, :dependent => :nullify

product.rb belongs_to :category belongs_to :label

所以我认为最好的方法是显示与所选产品belongs_to相同类别的随机产品?

目前这是我在products_controller.rb 中的def show 行中所拥有的

@products_rand = Product.offset(offset).limit(6)

我需要它来只抓取与所选产品相同类别的产品吗?

products_controller.rb

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


     def show
      offset = rand(100)
       @meta_title = "Mypage #{@product.title}"
       @meta_description = @product.description
      @products_rand = Product.offset(offset).limit(6)
     end

    private
     def set_product
      @product = Product.find(params[:id])
     end

    def product_params
      params.require(:product).permit(:title, :description, :image, :category_id, :stock_quantity, :label_id, :query, :slug)
    end


 end

并且随机产品显示在这个views/products/show.html.erb

  <div class="row product-teaser">

  <h4 class="text-center teaser-text"> Products from same category </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 %>
         <%= image_tag product.image.url, :size => "100%x100%", class: "img-responsive center-block" %>
       <% end %>

          <h5 class="text-center"><%= link_to product.title, product, class: "text-center" %></h5>

      </div>
      <% end %>

  </div>

这里是关于这个Not able to display random images below product image in Ruby on rails app?的上一个问题的链接

【问题讨论】:

    标签: ruby-on-rails ruby postgresql random many-to-many


    【解决方案1】:

    您可以使用以下内容(对于 Postgres/SQLite):

    @products_rand = Product.where(category_id: @product.category_id).order("RANDOM()").limit(6)
    

    MySQL 或以下内容:

    @products_rand = Product.where(category_id: @product.category_id).order("RAND()").limit(6)
    

    【讨论】:

    • 谢谢,postgres 版本有效。是否可以从随机产品中排除所选产品?
    • 您或许可以使用where.not.(id: @product.id)
    • 我没用过where.not.,应该用它来代替where吗?
    猜你喜欢
    • 2017-10-10
    • 2013-09-09
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2020-09-18
    相关资源
    最近更新 更多