How to parameterize enum? I need to use the enum for parameter which has an integer value as a data type.
models/product.rb
class Product < ActiveRecord::Base
enum category_id: [ :hotel, :travel, :restaurant ]
end
views/products/sidebar
<div class="col-md-3">
<ul class="list-group">
<li class="list-group-item">
<span class="badge"><%= Product.where(user_id: current_user).count %></span>
<a href="<%= provider_root_path %>">All</a>
</li>
<% @categories.each do |category| %>
<li class="list-group-item">
<span class="badge"><%= Product.where(category_id: category[1]).count %></span>
<a href="<%= provider_product_category_path(category[0].parameterize) %>"><%= category[0].titleize %></a>
</li>
<% end %>
</ul>
</div>
this line works exactly what I want:
<%= product_category_path(category[0].parameterize) %>
it produces:
'/product/category/travel'
and here is my problem:
controllers/product_controller.rb
def category
@products = Product.where(category_id: params[:category_id]).order("created_at DESC")
@categories = @products.category_ids
end
I need to change the params[:category_id]
to integer. I have try params[:category_id].to_i
but it always return 0.
Can anybody help? thanks in advance :)
To get product successful, you need:
Product.where(category_id: params[:category_id].to_sym).order(anything_you_want)
To get strictly integer, you need to:
Product.category_ids[params[:category_id].to_sym]