Brian Stanwyck
Brian Stanwyck

Reputation: 21

Rails validates_with error: :attributes cannot be blank

I'm trying to use a validates_with validation to some code that makes sure two flags aren't both simultaneously true:

validates_with ConfirmationValidator

class ConfirmationValidator < ActiveModel::Validator
  def validate(record)
    if record.confirmed_good && record.confirmed_bad
      record.errors[:base] << "Record is both confirmed and confirmed_bad"
    end
  end
end

But attempting to use this gets the following error:

gems/activemodel-3.0.7/lib/active_model/validator.rb:142:in `initialize': :attributes cannot be blank (RuntimeError)

Looking through that file makes it seem like this is due to some problem passing options, but I still can't quite tell what's going wrong. Any ideas?

Upvotes: 2

Views: 3641

Answers (2)

juliangonzalez
juliangonzalez

Reputation: 4381

This can happen if you name your validator the same name a Rails validator has been named. Example, naming you validator:

PresenceValidator will lead to this exception.

Upvotes: 1

Chewbarkla
Chewbarkla

Reputation: 329

As @Gazler points out above, your error actually maps to an EachValiator initialization problem. I ran into the same problem.

I'm running rails 3.0.9, using ActiveModel 3.0.9, not quite the same stack you seem to be running. I'm just beginning with custom validators. I have a ActiveModel::EachValidator, not quite what your code sample says. The EachValidator needs attributes passed as an array within the options to validates_with, e.g.

class Something < ActiveRecord::Base
  validates_with GenericValidator, :attributes=>[:name, :image]
end

Upvotes: 6

Related Questions