I have an application where I have added a sidebar with a list of all the categories the products belong to.
The feature works fine but there is a problem.
The code only scans through the products on the current page and not the actual categories available. That is:
In my application there are say 5 categories (which there are) of products but on the current page there are only 3 products. So the code only shows me 3 categories and not the actual 5.
How can I fix this? Does this have anything to do with instance variables?
Here is the code from application.html.erb
<div>
<% a = [""] %>
<h1>Categories</h1>
<% @products.each do |product| %>
<% a = a + [product.category] %>
<% a = a.uniq %>
<% end %>
<% a.each do |c| %>
<p class="text-error"><%= c %></p>
<% end %>
</div>
Migration files..
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.date :delivery_date
t.decimal :price
t.timestamps
end
end
end
class CreateCommentsTable < ActiveRecord::Migration
def up
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :product
t.timestamps
end
add_index :comments, :product_id
end
def down
end
end
class AddCategoryToProducts < ActiveRecord::Migration
def change
add_column :products, :category, :string
end
end
Routes..
resources :products do
resources :comments
end
The code is available at https://github.com/abhishekdagarit/sample-app.git
Might take u people just a quick look to answer this…
If you have separate
Categorymodel mapped tocategoriestable thenCategory.select(:name).uniqwould have return unique categories.In your case you have category column withing the table. So in that case
Product.select(:category).uniqwould return list of Products with unique categories.So now you template would be cleaner with: