1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Revises examples in the callbacks guide [skip ci]

As a rule of thumb, models are not supposed to be sending emails. Typically, in
a simple application, controller actions are the ones responsible for gluing
things together.

Ideally, creating a user in the console, runner, or test suite, should not
generate an email. That typically happens on a "sign up", which is a higher
level concept. Again, generally speaking.

As any rule of thumb, you may find exceptions, use always your best judgement.
This does not mean sending an email from a callback is categorically wrong, it
just means it is not something you'd generally want to do.

Documentation examples should be a model for readers. Better pick different,
more neutral examples here.

Thanks to @solnic for commenting this example existed.
This commit is contained in:
Xavier Noria 2021-06-02 22:48:53 +02:00
parent 269cac73a1
commit c9614442b2

View file

@ -368,26 +368,26 @@ class Order < ApplicationRecord
end
```
### Multiple Conditions for Callbacks
### Using both :if and :unless
When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration:
Callbacks can mix both `:if` and `:unless` in the same declaration:
```ruby
class Comment < ApplicationRecord
after_create :send_email_to_author, if: :author_wants_emails?,
unless: Proc.new { |comment| comment.article.ignore_comments? }
before_save :filter_content,
if: Proc.new { forum.parental_control? },
unless: Proc.new { author.trusted? }
end
```
### Combining Callback Conditions
### Multiple Callback Conditions
When multiple conditions define whether or not a callback should happen, an `Array` can be used. Moreover, you can apply both `:if` and `:unless` to the same callback.
The `:if` and `:unless` options also accept an array of procs or method names as symbols:
```ruby
class Comment < ApplicationRecord
after_create :send_email_to_author,
if: [Proc.new { |c| c.user.allow_send_email? }, :author_wants_emails?],
unless: Proc.new { |c| c.article.ignore_comments? }
before_save :filter_content,
if: [:subject_to_parental_control?, :untrusted_author?]
end
```