简体   繁体   English

Rails 4枚举验证

[英]Rails 4 enum validation

This is the first time I'm using enums with rails 4 and I ran into some issues, have couple of dirty solutions in mind and wanted to check are there any more elegant solutions in place : 这是我第一次使用带有rails 4的枚举,我遇到了一些问题,考虑了几个肮脏的解决方案,并想检查是否有更优雅的解决方案:

This is my table migration relevant part: 这是我的表迁移相关部分:

create_table :shippings do |t|
  t.column :status, :integer, default: 0
end

My model: 我的模特:

class Shipping < ActiveRecord::Base
  enum status: { initial_status: 0, frozen: 1, processed: 2 }
end

And I have this bit in my view (using simple form for) : 在我看来,我有这一点(使用简单的形式):

= f.input :status, :as => :select, :collection => Shipping.statuses, :required => true, :prompt => 'Please select', label: false

So in my controller: 所以在我的控制器中:

  def create
    @shipping = Shipping.create!(shipping_params)

    if @shipping.new_record?
      return render 'new'
    end

    flash[:success] = 'Shipping saved successfully'
    redirect_to home_path
  end

private

  def shipping_params
    params.require(:shipping).permit(... :status)
  end

So when I submit create form and the create action fire I get this validation error : 因此,当我提交create form和create action fire时,我收到此验证错误:

'1' is not a valid status

So I thought I knew that the issue was data type so I added this bit in the model : 所以我认为我知道问题是数据类型所以我在模型中添加了这个位:

before_validation :set_status_type

  def set_status_type
    self.status = status.to_i
  end

But this didn't seem to do anything, how do I resolve this ? 但这似乎没有做任何事情,我该如何解决这个问题呢? Has anyone had the similar experience? 有没有人有类似的经历?

You can find the solution here . 你可以在这里找到解决方案。

Basically, you need to pass the string ('initial_status', 'frozen' or 'processed'), not the integer. 基本上,您需要传递字符串('initial_status','frozen'或'processed'),而不是整数。 In other words, your form needs to look like this: 换句话说,您的表单需要如下所示:

<select ...><option value="frozen">frozen</option>...</select>

You can achieve this by doing statuses.keys in your form. 您可以通过在表单中​​执行statuses.keys来实现此目的。 Also (I believe) you don't need the before_validation . 另外(我相信)你不需要before_validation

Optionally, you could add a validation like this: 或者,您可以添加如下验证:

validates_inclusion_of :status, in: Shipping.statuses.keys

However, I'm not sure that this validation makes sense, since trying to assign an invalid value to status raises an ArgumentError ( see this ). 但是,我不确定这种验证是否有意义,因为尝试为状态分配无效值会引发ArgumentError( 请参阅此内容 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM