AnthonyGalli.com AnthonyGalli.com - 1 month ago 6
Ruby Question

Conditional Validation for Serialized Array

How can I create a validation where

committed
presence needs to be true only if the challenge's category is
habit
?

class Challenge < ActiveRecord::Base
CATEGORY = ['goal', 'habit']
serialize :committed, Array
validates :committed, presence: true, if: :habit # I also tried with 'habit' & 'Habit'
end

Answer

Since your category is called 'habit' (note, it is not 'Habit'), the validation would look as follows:

validates :committed, presence: true, if: ->(c) { c.category == 'habit' }

As a sidenote: I do not think your scopes will work, unless you have a column called categories in your challenges table. Thus, if your intention was to select challenges, which have category 'habit', the scope would look as follows:

scope :habit, -> { where(category: 'habit') }

EDIT

As per discussion in comments, if you want committed to be nil instead of [""] when nothing is there, add custom validation:

validate :committed_content

private

def committed_content
  self.committed = nil if committed.empty? || committed.all?(&:blank?)
  true
end
Comments