Search code examples
ruby-on-railsrubypostgresqlrandommany-to-many

Displaying random products in ruby on rails app


In a app I'm building, a customer selects a product and in the products/show.html.erb he is supposed to be able to see related products in a below div.

category.rb and product.rb are related:

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

product.rb belongs_to :category belongs_to :label

So Im thinking the best way to do that is to display random products from the same category as the selected product belongs_to?

At the moment this what I have in the def show line in the products_controller.rb

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

I need it to grab only products in the same category as the selected product?

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

And the random products are displayed in this the 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>

Here is a link to previous question about this Not able to display random images below product image in Ruby on rails app?


Solution

  • You can use the following (for Postgres/SQLite):

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

    Or the following for MySQL:

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