mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Skip Validations When Creating A Record as a Rails til
This commit is contained in:
@@ -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)
|
||||
|
||||
35
rails/skip-validations-when-creating-a-record.md
Normal file
35
rails/skip-validations-when-creating-a-record.md
Normal file
@@ -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.
|
||||
Reference in New Issue
Block a user