Ruby on Rails Wednesday, November 21, 2018

After a while of development your project, you might notice that you have some inconsistencies between your database constraints and validations. Right now, we will talk about two possible situations.

Case #1.

Imagine you defined your table as following:


create_table :users do |t|
  t
.string :name
end
 

And your model definition:


class User < ApplicationRecord
  validates
:email, presence: true
end
 

In this case, the validation can be skipped by some methods and the null value will be inserted in the database. In most cases, you probably don't want this to happen so it's better to have not null constraint in the database.


Case #2.


Imagine you defined your table as following:


create_table :users do |t|
  t
.string :name, null: false
end

And your model definition:


class User < ApplicationRecord
end

In this case, the valid? method will return true for the records which cannot be created. Moreover, the attempt to insert a row will execute from 1 up to a few SQL queries and in a result raise an error and rollback the whole transaction. Those all things are very inefficient and can be easily skipped by just adding presence validation. You should add it in most cases.

So the question is how to find all possible issues automatically without manually checking all models?

Here database_consistency gem comes in handy. Right now, it detects most of issues. Also, it helps us to detect the issue where a column has not-null constraint but there is possible null insert defined by the optional presence validator.

Try it yourself and share your feedback. Feel free to contribute! Any thoughts are welcome!

P.S. This is my own topic was copy-pasted from reddit to spread the info about the gem. 

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/60622ef3-b359-4d29-878a-afa792a81695%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment