Rails 4 如何参数化枚举

Rails 4 how to parameterize enum

如何参数化枚举?我需要使用枚举作为数据类型为整数值的参数。

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>

这条线正是我想要的:

<%= product_category_path(category[0].parameterize) %>

它产生:

'/product/category/travel'

这是我的问题:

controllers/product_controller.rb

def category
  @products = Product.where(category_id: params[:category_id]).order("created_at DESC")
  @categories = @products.category_ids
end

我需要将 params[:category_id] 更改为整数。我试过 params[:category_id].to_i 但它总是 return 0.

有人可以帮忙吗?提前致谢:)

要使产品成功,您需要:

Product.where(category_id: params[:category_id].to_sym).order(anything_you_want)

要获得严格的整数,您需要:

Product.category_ids[params[:category_id].to_sym]