title: Displaying random products in ruby on rails app
body: <p>In a app I'm building, a customer selects a product and in the <code>products/show.html.erb</code> he is supposed to be able to see related products in a below div.  </p>
  
  <p>category.rb and product.rb are related:</p>
  
  <p><code>cateory.rb
      has_many :products, :dependent =&gt; :nullify</code></p>
  
  <p><code>product.rb
    belongs_to :category
      belongs_to :label</code></p>
  
  <p>So Im thinking the best way to do that is to display random products from the same category as the selected product <code>belongs_to</code>?</p>
  
  <p>At the moment this what I have in the <code>def show</code>  line in the <code>products_controller.rb</code></p>
  
  <pre><code>@products_rand = Product.offset(offset).limit(6)
  </code></pre>
  
  <p>I need it to grab only products in the same category as the selected product?  </p>
  
  <p><code>products_controller.rb</code></p>
  
  <pre><code> class ProductsController &lt; 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
  </code></pre>
  
  <p>And the random products are displayed in this the <code>views/products/show.html.erb</code></p>
  
  <pre><code>  &lt;div class="row product-teaser"&gt;
  
    &lt;h4 class="text-center teaser-text"&gt; Products from same category &lt;/h4&gt;
     &lt;% @products_rand.each do |product| %&gt;
        &lt;div class="col-sm-2 col-xs-3 center-block product-thumbs-product-view" &gt;
  
         &lt;%= link_to product_path (product) do %&gt;
           &lt;%= image_tag product.image.url, :size =&gt; "100%x100%", class: "img-responsive center-block" %&gt;
         &lt;% end %&gt;
  
            &lt;h5 class="text-center"&gt;&lt;%= link_to product.title, product, class: "text-center" %&gt;&lt;/h5&gt;
  
        &lt;/div&gt;
        &lt;% end %&gt;
  
    &lt;/div&gt;
  </code></pre>
  
  <p>Here is a link to previous question about this <a href="https://stackoverflow.com/questions/43920636/not-able-to-display-random-images-below-product-image-in-ruby-on-rails-app">Not able to display random images below product image in Ruby on rails app?</a></p>