Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an enum value in an :if validation

Tags:

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.

like image 467
Timmy Von Heiss Avatar asked Dec 14 '17 21:12

Timmy Von Heiss


2 Answers

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

like image 118
Shiko Avatar answered Sep 21 '22 12:09

Shiko


Short version:

validates_presence_of :explanation, if: 'extended?'
like image 36
mmsilviu Avatar answered Sep 21 '22 12:09

mmsilviu