【发布时间】:2014-07-10 07:59:34
【问题描述】:
我正在尝试使用已添加到 Rails 的枚举功能。我已经等了很久了。
我是这样设置的:
产品型号:
enum category: [:t_shirt, :hoodie, :jacket]
产品负责人:
def create
@product = Product.new(product_params)
if @product.save
redirect_to @product, notice: 'Product was successfully created.' }
else
render :new
end
end
def product_params
params.require(:product).permit(:title, :description, :category, :price)
end
新表单
<%= form_for(@product) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :price %><br>
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :category %><br>
<%= f.select :category, Product.categories, include_blank: "Select a category" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
这会使用我在模型中定义的不同枚举选项的值正确填充表单中的下拉字段。
但是,当我提交从下拉列表中选择了一个类别的表单时,它给了我一个错误:
'0' is not a valid category
即使我的类别字段是一个整数字段,并且“0”是与我在表单中选择的类别相关联的正确整数。
它还突出显示了我的产品控制器中的 create 方法中的以下行作为发生错误的地方:
@product = Product.new(product_params)
我完全不知道为什么会这样。非常感谢一些帮助。
谢谢。
【问题讨论】:
-
Product.categories有什么价值?还在表单提交上发布您的server log。 -
您的
enum名称是category还是categories? -
@Pavan 这个权利
Product.categories提供enum值的散列 -
对不起大家的回复延迟。是的Зелёный下面的答案是正确的并且解决了问题。感谢大家的贡献。
标签: ruby-on-rails ruby-on-rails-4 enums