1

I have a model and I am using Single Table Inheritance. This has a type column in my database which is populated with the string of the class name.

Should I validate this column?

Options:

  • required column in the db
  • validates :type, presence: true
  • validates :type, inclusion: {in: [Class1.to_s, Class2.to_s]}
John Hinnegan
  • 5,864
  • 2
  • 48
  • 64

2 Answers2

2

Since ActiveRecord handles the type field you don't need to write extra validations on this field.

Loqman
  • 1,487
  • 1
  • 12
  • 24
1

I agree that none of these validations are required.

Just to elaborate, validations handle human input from a form. They exist to deal with one specific concern, and that’s to ensure user input data fits an acceptable format.

  • there’s no need to validate that any column is in the database if that table is created by your Rails application. The migrations put it there and if people are dropping columns from your database you’ve got bigger problems than validating user input.
  • there’s no need to validate the presence of a type field, if it’s empty it will be automatically populated with the instantiated class. E.g. Parent.new will fill it with “Parent”
  • There may be some value to validating inclusion, but it would be very rare for it to be possible to input an invalid type. If your user has to type the name of a class in to a form, there’s some very fishy form design in play. Instead take one of these two approaches:
    • A select containing the valid types.
    • Separate controllers for each child type. After all, if they’re significantly different, you’ll probably want their forms, show pages and index pages to look different. And if they’re not significantly different, you probably don’t want to use single table inheritance.

(With either of those approaches, there’s no need to validate the type column)

Hope this helps :)

AJFaraday
  • 2,411
  • 1
  • 16
  • 39