0

Subclass validations as well as superclass validations implemented. How to discard superclass validations in subclass?
My code:

class a < ActiveRecord::Base
  validates_presence_of :price
end

class a2 < a
  validates_presence_of :price
end

When I am creating a object for a2, using following command:

x = a2.new
x.save

the following errors are displayed:

x.errors.full_messages
=> ['price can't be blank','price can't be blank']

How can I resolve this, so that validations of superclass are ignored.

skadoosh
  • 471
  • 1
  • 6
  • 15

2 Answers2

0

The two error messages are expected according to your code.

What you did on inherited model is to add one more validation to the validation chain, instead of overwrite it.

Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • How can I overwrite it? – skadoosh Aug 23 '13 at 11:55
  • It seems not so easy and no convention way. check here: http://stackoverflow.com/questions/2309757/removing-or-overriding-an-activerecord-validation-added-by-a-superclass-or-mixin My opinion, if the super class is written by you, don't write such validators there. – Billy Chan Aug 23 '13 at 12:02
  • Thank you, I managed the validations using :if => 'called a function that checks the class', i.e. x.class == a – skadoosh Aug 23 '13 at 12:52
  • @schipitch, it's okay you solved it though I don't like this. The super class managed something not belonging to him. – Billy Chan Aug 23 '13 at 13:06
  • I know, it is a temporary fix, I will anyhow get rid of the subclass soon, that's why, but i will still try to see if there is an easier and better way. – skadoosh Aug 25 '13 at 07:47
  • @schipitch, check this: http://stackoverflow.com/a/692448. Similar to your method but better because parent class doesn't mention children's names. – Billy Chan Aug 25 '13 at 07:52
  • Yeah, this is an easier method, good, I will try this out, thanks. – skadoosh Aug 25 '13 at 08:03
0

I tried using "Add to errors" unless errors.added? which works fine.

user1190286
  • 106
  • 2