在 Rails 4.1 中从选择中保存枚举 [英] Saving enum from select in Rails 4.1

查看:30
本文介绍了在 Rails 4.1 中从选择中保存枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Rails 4.1 中的枚举来跟踪酒的颜色.

I am using the enums in Rails 4.1 to keep track of colors of wine.

Wine.rb

class Wine < ActiveRecord::Base
    enum color: [:red, :white, :sparkling]
end

在我看来,我生成了一个选择,以便用户可以选择具有特定颜色的酒

In my view, I generate a select so the user can select a wine with a certain color

f.input :color, :as => :select, :collection => Wine.colors

这会生成以下 HTML:

This generates the following HTML:

<select id="wine_color" name="wine[color]">
  <option value=""></option>
  <option value="0">red</option>
  <option value="1">white</option>
  <option value="2">sparkling</option>
</select>

但是,在提交表单时,我收到一个参数错误,指出 '1' 不是有效颜色.我意识到这是因为 color 必须等于 1 而不是 "1".

However, upon submitting the form, I receive an argument error stating '1' is not a valid color. I realize this is because color must equal 1 and not "1".

有没有办法强制 Rails 将颜色解释为整数而不是字符串?

Is there a way to force Rails to interpret the color as an integer rather than a string?

推荐答案

好吧,显然,您不应该发送要保存的枚举的整数值.您应该发送枚举的文本值.

Alright, so apparently, you shouldn't send the integer value of the enum to be saved. You should send the text value of the enum.

我将输入更改为以下内容:

I changed the input to be the following:

f.input :color, :as => :select, :collection => Wine.colors.keys.to_a

生成以下 HTML:

<select id="wine_color" name="wine[color]">
  <option value=""></option>
  <option value="red">red</option>
  <option value="white">white</option>
  <option value="sparkling">sparkling</option>
</select>

值从0"开始到红色"现在我们都准备好了.

Values went from "0" to "red" and now we're all set.

如果您使用的是常规的 ol' rails text_field,则为:

If you're using a regular ol' rails text_field it's:

f.select :color, Wine.colors.keys.to_a


如果你想拥有干净的人类可读的属性,你也可以这样做:


If you want to have clean human-readable attributes you can also do:

f.select :color, Wine.colors.keys.map { |w| [w.humanize, w] }

这篇关于在 Rails 4.1 中从选择中保存枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆