TIL:以前的新记录?- ActiveRecord 中隐藏的珍宝

TIL: previously_new_record? — A Hidden Gem in ActiveRecord
作者:Glauco Custodio    发布时间:2025-07-04 12:51:56    浏览次数:0
Have you ever needed to know if a record in Rails was just created — especially after using create_or_find_by or find_or_create_by ?

Most Rails devs reach for new_record? , but it won’t help after create_or_find_by , because the record is already saved. So how do you know if a record was just created?

Say hello to previously_new_record? , which for my surprise is available since Rails 6.1.

It tells you if the record was new right before the last save — giving you a clean way to trigger onboarding logic, log metadata, or set defaults only for new records.

Here's how one can use it:

user = User . create_or_find_by ( email: params [ :email ]) # only create the log if the user was just created if user . previously_new_record? create_log ( user ) end

Next time you need to distinguish between a found and a created record, reach for previously_new_record? . It’s already part of ActiveRecord — no extra setup needed.

You can check out how it was implemented in this pull request.

最新文章

热门文章