如何在:如果验证中使用枚举值

时间:2017-12-14 21:31:48

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

假设我们有一个枚举

enum status: { pending: 0, finished: 1, extended: 2 }

我们希望根据枚举状态值

创建验证
validates_presence_of :explanation, if: ...enum status is equal to "extended"

我一直都是蛮力,尝试了很多组合,但似乎找不到任何有用的东西。

2 个答案:

答案 0 :(得分:2)

您可以使用pending?

评估您的字段
class Job < ActiveRecord::Base
  enum status: [ :active, :archived ]
  validates_presence_of :explanation, if: Proc.new { |a| a.extended? }
end

完整示例:

class Conversation < ActiveRecord::Base
  enum status: [ :active, :archived ]
end

# conversation.update! status: 0
conversation.active!
conversation.active? # => true
conversation.status  # => "active"

# conversation.update! status: 1
conversation.archived!
conversation.archived? # => true
conversation.status    # => "archived"

# conversation.status = 1
conversation.status = "archived"

conversation.status = nil
conversation.status.nil? # => true
conversation.status      # => nil

<强>参考:
http://api.rubyonrails.org/classes/ActiveRecord/Enum.html

答案 1 :(得分:0)

简短版本:

validates_presence_of :explanation, if: 'extended?'