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

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

问题描述

我正在使用Rails 4.1中的枚举来跟踪葡萄酒的颜色。



Wine.rb

  class Wine< ActiveRecord :: Base 
枚举颜色:[:红色,白色,闪闪发光]
结束

在我看来,我产生一个选择,所以用户可以选择一种具有某种颜色的葡萄酒

  f。输入:颜色,:as => :select,:collection => Wine.colors 

这会生成以下HTML:

 < select id =wine_colorname =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



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

解决方案

好的,很明显,你不应该发送要保存的枚举的整数值。您应该发送枚举的文本值。



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



f.input:color,:as => :select,:collection =>其中生成以下HTML:



<$ p



$ p> < select id =wine_colorname =wine [color]>
< option value =>< / option>
< option value =red> red< / option>
< option value =white> white< / option>
< option value =sparkling> sparkling< / option>
< / select>

值从0变为红色,现在我们都设置好了。






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



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






如果您想拥有干净的人性化属性,您还可以执行以下操作:



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


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

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>

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".

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

Which generated the following 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>

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


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中的select中保存枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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