假设我们有一个枚举
enum status: { pending: 0, finished: 1, extended: 2 }
我们希望根据枚举状态值
创建验证validates_presence_of :explanation, if: ...enum status is equal to "extended"
我一直都是蛮力,尝试了很多组合,但似乎找不到任何有用的东西。
答案 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?'