枚举数值验证失败

时间:2015-11-10 09:35:31

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

Rails 4.2
Ruby 2.1.2

order.rb

  class Order < ActiveRecord::Base
   enum delivery_status: {
         waiting_to_accept: 0,
         accepted_order: 1,
         order_placed: 2,
         order_confirmed: 3,
         arrived_at_restaurant: 4,
         picked_up_items: 5,
         en_route: 6,
         delivered: 7,
         cancelled: 8
       }
    validates :delivery_status, numericality: { :greater_than_or_equal_to => 0, :less_than_or_equal_to => 7 }
   end

我试图通过delivery_status验证,但没有成功。

2.1.2 :075 > o = Order.new 
2.1.2 :076 > o.delivery_status = 1
 => 1 
2.1.2 :077 > o.valid?
 => false 
2.1.2 :078 > o.errors.full_messages.grep /delivery status/i
 => ["Delivery status is not a number"] 
2.1.2 :079 > o.delivery_status = :waiting_to_accept
 => :waiting_to_accept 
2.1.2 :080 > o.valid?
 => false 
2.1.2 :081 > o.errors.full_messages.grep /delivery status/i
 => ["Delivery status is not a number"]

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要使用inclusion:来验证枚举。

validates :delivery_status, :inclusion => { :in => [:waiting_to_accept, :accepted_order, :order_placed, :order_confirmed, :arrived_at_restaurant, :picked_up_items, :en_route, :delivered, :cancelled] }