- 11 months ago 51
Ruby Question

Conditional Validation for Serialized Array

How can I create a validation where

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

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

Answer Source

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') }


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

validate :committed_content


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