From ebe8b38a93f0e9224ba96f192ff2714576944980 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 5 Jan 2021 12:51:19 -0600 Subject: [PATCH] Add Skip Validations When Creating A Record as a Rails til --- README.md | 3 +- ...skip-validations-when-creating-a-record.md | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 rails/skip-validations-when-creating-a-record.md diff --git a/README.md b/README.md index 40b8d90..1e3b80d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_994 TILs and counting..._ +_996 TILs and counting..._ --- @@ -656,6 +656,7 @@ _994 TILs and counting..._ - [Show Pending Migrations](rails/show-pending-migrations.md) - [Show Rails Models With Pry](rails/show-rails-models-with-pry.md) - [Show Rails Routes With Pry](rails/show-rails-routes-with-pry.md) +- [Skip Validations When Creating A Record](rails/skip-validations-when-creating-a-record.md) - [Temporarily Disable strong_params](rails/temporarily-disable-strong-params.md) - [Test If An Instance Variable Was Assigned](rails/test-if-an-instance-variable-was-assigned.md) - [Truncate Almost All Tables](rails/truncate-almost-all-tables.md) diff --git a/rails/skip-validations-when-creating-a-record.md b/rails/skip-validations-when-creating-a-record.md new file mode 100644 index 0000000..a47ff66 --- /dev/null +++ b/rails/skip-validations-when-creating-a-record.md @@ -0,0 +1,35 @@ +# Skip Validations When Creating A Record + +Validations on your +[ActiveRecord](https://api.rubyonrails.org/classes/ActiveRecord/Base.html) +models are there for a reason. They provide application-level feedback about +data that doesn't meet business requirements. In many cases those validations +should also be pushed down to the database-layer in the form of constraints. + +Sometimes, though rarely and probably only in a testing or development context, +you'll want to skip validations. + +This is how you can do that when creating a new record: + +```ruby +user = User.new( + name: 'Josh', + email: '', + password: SecureRandom.uuid +) + +user.valid? +#=> false +user.errors.messages +#=> {:email=>["can't be blank"]} + +user.save(validate: false) +``` + +After newing-up an object with invalid data, you can [save it with the +`validate` option set to +`false`](https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-save). +This will skip ActiveRecord validations. + +Note: If you also have a database-layer constraint, this won't work. Perhaps +for your use case you can get by with a new non-persisted record.