TIL: Previously_new_record? – A Hidden Gem in ActiveRecord

4 months ago 3

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.

Read Entire Article