Muhammed kanyi
Muhammed kanyi

Reputation: 89

how to show products under the categories on rails

am working on a rails app and on the show page for a category, i want to show all the products found under that category here is how my

show in category is

def show
    @products = Category.friendly.where(params[:name])
  end

and in my views i have it like this

<% @products.each do |product| %>

<%= link_to product_path(id: product.slug, category_name: product.category.name), class: "card" do %>
<div class="product-image">
<%= image_tag product.productpic.url if product.productpic? %>
</div>

  <div class="product-text">
    <h2 class="product-title"> <%= product.name %></h2>
      <h3 class="product-price">£<%= product.price %></h3>
  </div>

    <% end %>
<% end %>

here is my products model

class Product < ApplicationRecord
  belongs_to :category
  mount_uploader :productpic, ProductpicUploader
   has_many :order_items
acts_as_taggable
extend FriendlyId
friendly_id :name, use: [:slugged, :finders]
 default_scope { where(active: true) }
end

and my category like this

class Category < ApplicationRecord
  has_many :products
  extend FriendlyId
 friendly_id :name, use: [:slugged, :finders]
end

what am i doing wrong here?

Upvotes: 0

Views: 1586

Answers (3)

user1201917
user1201917

Reputation: 1370

You finder gets the categories, not the products:

def show
  @categories = Category.friendly.where(params[:name])
end

If you have proper relations, you can iterate each product in the given category. Since the method where returns relation, first you need is iterate through it.

<% @categories.each do |category| %>
  <% category.each do |product| %>
    <div class="product-category">
      Category:
      <%= product.category.name %>
    </div>
    <div class="product-text">
      <h2 class="product-title"> <%= product.name %></h2>
      <h3 class="product-price">£<%= product.price %></h3>
    </div>
  <% end %>
<% end %>

Upvotes: 1

Navin
Navin

Reputation: 924

Try this,

def show
  category = Category.friendly.find_by_name(params[:name])
  @products = category.products
end

Upvotes: 0

Kushal
Kushal

Reputation: 352

you are executing a wrong query. You are taking category that is fine but you have to take related products that is what you need.

it should be like, @products = Category.friendly.where(name: params[:name]).first.products

then in the view code, you can iterate over products of a category.

Upvotes: 0

Related Questions