【问题标题】:Rails enum not saving to database from select optionsRails 枚举未从选择选项保存到数据库
【发布时间】:2015-11-06 06:46:44
【问题描述】:

这是我的表格:

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!'

为什么会这样?

【问题讨论】:

  • @wiesion 请查看我更新的问题
  • 您的原始问题是重复的,而您的编辑使这是一个新问题。还提供更多来自错误堆栈跟踪的内容,只是来自github.com/rails/rails/blob/4-2-stable/activerecord/lib/… 的“Failed to save the record ... :in save!”对调试没有帮助。
  • 问题是在 Rails 服务器控制台中没有错误抛出,只回滚一些查询,我使用 pry.save! 任何想法得到上述消息。我真的关注了你可能重复的问题链接

标签: ruby-on-rails activerecord enums


【解决方案1】:

此表单 sn-p 提交的值不会验证,因为 update 需要“字符串”键,而不是表的基础数值。

相反,您可以使用以下内容:

<%=  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) %>

【讨论】:

  • 更新了我的答案。可以再试一次吗?让我知道其中任何一个是否有效。
  • 同样的事情,它在第一次加载时返回错误,离我想要的很远,但是谢谢男人
  • 你能用Promo.categories,map{|k,v| [k,k]}试试吗?
  • Promo.categories,map{|k,v| [v,v]}
  • 同样的事情,视图已经解决了,我现在的问题是它无法保存到数据库中
猜你喜欢
  • 2014-07-04
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 2011-01-14
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多