Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check to see if record is newly created

I can't figure out how to check to see if a record is newly saved. right now I am using

 If @item.save
      @a = Item.where(“restaurant_id = ?”, params[:item][:user_id]).where(“created_at < ?”, 2.minutes.ago)

The query is working fine but I'm wondering if there is a better way to check to see if the record was just created. I was looking into ActiveModel::Dirty but once the record is saved, :created_at_changed? will return false.

like image 565
Ria Avatar asked Aug 25 '13 01:08

Ria


People also ask

How to check if the current record is a new record?

Determine whether the current record is a new record on Form Load. Look forward to kind reply. What do you mean by new record? A record that was recently created? You can get the record 'createdon' and get the current date and time then compare. You can also use getFormType. If the form is "Create" = New or "Update" = existing.

How to get the current record created/updated/deleted in Salesforce?

The first method is that you can create a Flow in the solution, and then use the When a record is created, updated or deleted included in the Common Data Service (current environment) connector as the trigger, and then check whether there is any in the trigger body that can be used Determine that the current record is created/updated/deleted.

What does was recently created mean in Salesforce?

wasRecentlyCreated indicates if the model was inserted during the current request lifecycle. So even if the record was missing from the DB, it will only return true after it is saved.

How to get the current date and time of a form?

You can get the record 'createdon' and get the current date and time then compare. You can also use getFormType. If the form is "Create" = New or "Update" = existing. You can refer to this microsoft page for more info.


1 Answers

For the record, Rails 4 and 5 now both have functionality for this.

In Rails 4, you can do:

@item.previous_changes.key?('id')

And in Rails 5:

@item.id_previously_changed?

[NOTE: This assumes you never manually update the IDs of your records. If you are, you'll need something more like the following:]

@item.previous_changes.key?('id') && @item.previous_changes['id'][0].nil?
like image 165
arthurlewis Avatar answered Oct 05 '22 07:10

arthurlewis