【问题标题】:rails 4.1 enums not saving from viewrails 4.1枚举不从视图中保存
【发布时间】:2014-02-08 12:02:03
【问题描述】:

Rails 4.1 提供了可用的枚举。我检查了它,它似乎在 Rails 控制台中运行良好。当我尝试通过控制器将数据从视图持久保存到数据库时,出现以下错误

“注册”不是有效的流类型

下面是我的课

class Stream < ActiveRecord::Base
  enum stream_type: { sales: 1, registration: 2, student: 3 }

  belongs_to :course_presentation

  has_many :subscriptions
  has_many :contacts, :through => :subscriptions

  validates :course_presentation_id, :stream_type, presence: true 
end

下面是我用来保存的代码

@stream = Stream.new(stream_params)

def stream_params
      params.require(:stream).permit(:stream_type, :course_presentation_id, :is_active, :created_by_user_id, :updated_by_user_id)
    end

下面是查看代码

<%= f.label :stream_type %><br>
    <%= f.collection_select :stream_type, StreamType.order(:name), :name, :name, include_blank: "<-- select -->" %>

有什么想法吗?我只是无法让它工作

【问题讨论】:

  • 你能显示你在发布什么吗?
  • 你在哪里定义StreamType

标签: ruby-on-rails enums ruby-on-rails-4


【解决方案1】:

我想通了,虽然对答案并不完全满意。存储枚举值的下拉列表是大写的。例如“登记”。尝试保存时找不到“注册”,但可以找到“注册”。用正确的大小写保存枚举就可以了。

无论如何,我希望我可以使用与哈希键对应的整数,但这似乎不起作用。

已编辑

解决这个问题的另一种方法是......

params.require(:stream).permit(:stream_type, :course_presentation_id, :is_active, :created_by_user_id, :updated_by_user_id).tap do |w|
      w[:stream_type] = w[:stream_type].to_i if w[:stream_type]
end

我发现了另一个帖子

Alternative solution

【讨论】:

  • Stream.new(stream_type: 1) 有效,但 Stream.new(stream_type: '1') 无效。由于 params[:stream_type] 将始终为 '1',因此它不起作用。 ActiveRecord 应该将其隐式转换为整数以使其正常工作。
  • 我在使用 Rails 4.1 时遇到了同样的问题。通过在保存或更新参数之前将值更改为整数来解决它。
  • 您可以为选择选项构建自定义集合来解决此问题。而不是通常的 [name, id],使用类似 [name.titleize, name] 的东西。关键是将名称分配为值,而不是像任何其他数据库字段那样分配 ID。
猜你喜欢
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
相关资源
最近更新 更多