Jake
Jake

Reputation: 1186

Ruby on Rails: Product categorization & display

I have a product page and 4 different category tabs. A created product can only belong to one of the 4 categories/tabs on the page. How could I choose the category the product belongs to via a form & How can I load the products belonging to each category?

My current setup for loading created products onto the page is this.

This is an example of ONLY ONE tab Category selection link...

<a href="#samplePacks" aria-controls="samplePacks" data-toggle="tab">
  <h2 class="base-text">Samples</h2>
  <%= image_tag("btn_Category_1.png", :alt => "Category one", class: "image-pad center") %>
</a>

Followed by its corresponding tab, linked to the selector above...

<div role="tabpanel" class="tab-pane fade in active" id="samplePacks">
  <div class="wellone pack-well">
    <div class="row" id="samplePillars">

      <% @packs.each do |pack| %>
        <div class="col-md-4 pack-pad">
          <%= link_to pack_path(pack) do %>
            <%= image_tag("#{pack.art_link}", :alt => "Product Image", :width => 333, :height => 333, class: "feat-img") %>
          <% end %>
        </div>
      <% end %>

    </div>
  </div>
</div>

When you click on any of the 4 tabs, you arrive at its unique category of items. There is no "display all items regardless of the category" each item cannot move from its category.

What is the code I need to add to the <% @packs.each do |pack| %> to load specific categories?

Thank you so much in advance.

Upvotes: 0

Views: 547

Answers (2)

Muhammed Anees
Muhammed Anees

Reputation: 1850


First you should have category_id in products table and then you need to setup the associations in Product and Category Model

class Product < ApplicationRecord
  belongs_to :category
end


and in Category Model

class Category < ApplicationRecord
  has_many :products
end

Now, in products/new.html.erb,

<%= form_for @product do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :category_id %><br>
  <%= f.collection_select :category_id, Category.all, :id, :name,prompt: "Select Category" %>
 <%= f.submit %>
<% end %>


And then you can make use of the association to show the products of each category with @category.products. Hope this will help

Upvotes: 1

Trenton Tyler
Trenton Tyler

Reputation: 1712

For what you are looking for you can use the collection_select.

collection_select(:product, :category_id, Category.all, :id, :category_name, prompt: true)

This is a good approach as it will load all dropdown options dynamically from your database.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

Upvotes: 1

Related Questions