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?