I have a restrictive schema (i.e. the schema already has null restrictions and maximum length etc). Would putting all of them in the model also overkill and counterproductive?…
validates :CouponID, :presence => true,
:numericality => true
validates :MerchantName, :presence => true,
:length => { :maximum => 100 }
validates :MerchantID, :presence => true,
:numericality => true
validates :Network, :length => { :maximum => 20 }
validates :Label, :presence => true
validates :CouponCode, :length => { :maximum => 100 }
validates :EndDate, :presence => true
validates :Link, :presence => true
validates :Status, :presence => true,
:length => { :maximum => 45 }
validates :Country, :length => { :maximum => 100 }
No it’s not an overkill. Putting these into validators your model would allow Rails to catch them before inserting them into the database. It’s also good design and practice.
If you omitted these, you would get MySQL errors thrown instead.
For example. Let’s say I have a
Commentmodel which contains an attribute string calledbodywhich can not be nil in my table.If I tried:
comment = Comment.create(body: nil)I would get the following exception.
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'body' cannot be null:This is bad. The natural flow of your application would break.
But, if I put the validators in my model like so
and tried the following:
comment = Comment.create(body: nil)I would not get an exception thrown but the
errorsarray for my variable to tell me what went wrong.It’s good practice to put validators in your models and allows for good design.