这是我的表格如下:
class Promo < ActiveRecord::Base {
:id => :integer,
:product_id => :integer,
:promo_code => :string,
:name => :string,
:description => :text,
:user_id => :string,
:email => :string,
:status => :integer,
:category => :integer,
:expire_date => :date,
:user_limit => :integer,
:created_at => :datetime,
:updated_at => :datetime
}
这是我的模特:
class Promo < ActiveRecord::Base
enum category: [ :discount, :rebate, :custom]
enum status: [ :offered, :claimed, :redeemed ]
end
和我的观点:
<%= f.select :category, options_for_select(Promo.categories.map { |w| w }, @promo.category) %>
将生成如下的html:
<select name="promo[category]" id="promo_category">
<option value="0">discount</option>
<option value="1">rebate</option>
<option value="2">custom</option>
</select>
但是当我尝试保存它时,它会抛出一个错误,上面写着:
'0' is not a valid category
如何将枚举保存到数据库?感谢
更新
之前我找到了这个链接。
我改变了我的观点:
<%= f.select :category, options_for_select(Promo.categories.keys.to_a.map { |w| [w.humanize, w] }, @promo.category) %>
但回到我的根本问题,它不起作用,它说:
ActiveRecord::RecordNotSaved: Failed to save the record
from /home/krismp/.rvm/gems/ruby-2.1.5/gems/activerecord-4.2.3/lib/active_record/persistence.rb:142:in `save!'
为什么会这样?
答案 0 :(得分:0)
此表单代码段提交的值不会验证,因为update需要“string”键,而不是表的基础数值。
相反,您可以使用以下内容:
<%= f.select :category, options_for_select(Promo.categories.map {|k,v| [k,k]}) %>
或
<%= f.select :category, options_for_select(Promo.categories.map {|k,v| [k,k]}, @promo.category) %>