0

I want to write an Active Record validation that throws an error when a user enters nothing at all in their form. Let's say the user has age and name properties, then it's fine if they don't enter age or don't enter name, but not entering both shouldn't happen. So I want something like this:

class User < ActiveRecord::Base
  validate :not_all_empty

   def not_all_empty
     if name.blank? && age.blank?
       errors.add (XXXX)
     end
   end
 end
user211309
  • 99
  • 1
  • 13

2 Answers2

1

Use the hash returned by .attributes and check its values, skipping the fields populated by ActiveRecord - timestamps and id.

def not_all_empty
  if attributes.except('id', 'created_at', 'updated_at').values.all?(&:blank?)
    errors.add ('XXXX')
  end
end
Bartosz Pietraszko
  • 1,367
  • 9
  • 9
0

The :allow_blank option is similar to the :allow_nil option. This option will let validation pass if the attribute's value is blank?, like nil or an empty string for example.

class User < ApplicationRecord
  validates :name, :age, allow_blank: true
end

The Documentation here!

LoganX
  • 29
  • 4
  • Thanks, I know about 'validates', but in my case the attributes are each optional, as long as there is at least one attribute filled in, whichever that might be. – user211309 Jun 18 '18 at 18:31
  • Please, read "2.10 absence, 3.1 :allow_nil, 3.2 :allow_blank" on the Documentation. I hope these "helper" and "option"s will help you to solve the your problem. – LoganX Jun 18 '18 at 18:47
  • @LoganX you have now allowed both of them to be blank which unfortunately is the current issue – engineersmnky Jun 18 '18 at 18:59
  • [https://stackoverflow.com/questions/2823628/rails-how-to-require-at-least-one-field-not-to-be-blank?noredirect=1&lq=1] This post may help you! – LoganX Jun 18 '18 at 19:03