Suppose that we have an enum
enum status: { pending: 0, finished: 1, extended: 2 }
And we want to create a validation based on the value of the enum status
validates_presence_of :explanation, if: ...enum status is equal to "extended"
I've been brute force, trying many combinations but can't seem to find anything that works.
You can evaluate your field using pending?
class Job < ActiveRecord::Base
enum status: [ :active, :archived ]
validates_presence_of :explanation, if: Proc.new { |a| a.extended? }
end
Complete example :
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
Reference:
http://api.rubyonrails.org/classes/ActiveRecord/Enum.html
Short version:
validates_presence_of :explanation, if: 'extended?'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With