Not logged in (Log in or Sign up)

unwwwritten

One or the other (but not both)

I ran into a validation today that rails didn't handle for me... or if it does, I didn't see how...

I wanted a model to contain field values that were exclusive of one another.

For example, an event model could have a schedule which ended either on a specific date or after a given number of repetitions, but not both.

In essence, I wanted...

   1  validates_one_of :repetitions, :repeat_until

So, I built it...

   1  module ValidatesOneOf
   2    def self.included(base)
   3      base.extend ClassMethods
   4    end
   5    
   6    module ClassMethods
   7      def validates_one_of(*attr_names)
   8        options = attr_names.extract_options!
   9        configuration = { :message => "Only one of #{attr_names.to_sentence(:connector => 'or')} should be provided.", :on => :save }
  10        configuration.update(options)
  11        options = configuration.symbolize_keys
  12        send(validation_method(options[:on] || :save), options) do |record|
  13          conflicts = attr_names.select { |a| record.send(a) }
  14          record.errors.add_to_base options[:message] if conflicts.size > 1
  15        end
  16      end
  17    end
  18  end

Now, I should probably add support for :allow_nil to specify that it's okay for none of the provided attributes to be set, but for now, that's the default.

blog comments powered by Disqus