简体   繁体   English

Rails 4如何参数化枚举

[英]Rails 4 how to parameterize enum

How to parameterize enum? 如何参数化枚举? I need to use the enum for parameter which has an integer value as a data type. 我需要对具有整数值的参数使用枚举作为数据类型。

models/product.rb 型号/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 控制器/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. 我需要将params[:category_id]更改为整数。 I have try params[:category_id].to_i but it always return 0. 我有尝试params[:category_id].to_i但它总是返回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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM