8

I was playing around with Rails admin and I noticed something.

Attributes which are defined as below in model, counted as "Required" in Rails admin

 validates :user, presence: true

However, attributes which are defined as below in table (schema/migration) still counted as "Optional"

t.datetime "created_at",:null => false

I would have assumed that both of these are identical except perhaps the level from which the validation error pops up. Am I wrong or is this a Rails admin error? Are both of these ensuring that this field will be required for a successful field save or is there a difference?

Karthik T
  • 31,456
  • 5
  • 68
  • 87

2 Answers2

9

Adding a :null => false means that this is a database restriction, i.e. under no circumstance will the database allow a null value.

Adding a presence: true is a model level validation so will take place before the object is inserted into the database. There may be a case you want to break these validations (for example edge cases or in your specs) You can then skip validation using :validates => false and the object will still go into the database, with a null DB restriction, this won't happen.

Alexsander Akers
  • 15,967
  • 12
  • 58
  • 83
Yule
  • 9,668
  • 3
  • 51
  • 72
  • Interesting, didnt know that I can opt out, so to speak, of validation. But besides that can I say that externally the behavior is the same? i.e I will not be able to save unless this property is assigned, in either case? – Karthik T Nov 14 '13 at 10:50
  • Yes, providing you always use the rails methods and don't pass `validates => false` – Yule Nov 14 '13 at 11:14
  • 1
    can you share a concrete example on why you would prefer to validate in the model instead of the DB ? – dowi Dec 28 '16 at 10:57
2
t.datetime "created_at",:null => false 

is telling the database not to accept null values. Whereas, validates :user, presence: true is like telling the Rails app to not accept null values. But it would be good to have them integrated, like having :null => false to also have it registered with Rails to have a model validation.

aartikriplani
  • 274
  • 2
  • 3