Ruby on Rails
Wednesday, October 21, 2015
First of all you should give a rigour definition of "newly_created?". I mean, what should we consider "newly created"? A record created 1 second ago? 10 mins ago, or 1 day ago?
On Wed, Oct 21, 2015 at 12:02 PM, Colin Law <clanlaw@gmail.com> wrote:
On 21 October 2015 at 07:42, Eugene Gilburg <eugene.gilburg@gmail.com> wrote:
> Several times I found myself of need of a method that tells whether an
> ActiveRecord instance has just been created. For example, when writing
> generic activity logging code that needs to know whether model is newly
> created as opposed to updated, but the invocation is in a service outside of
> the model itself and thus I can't just write `after_create` and
> `after_update` hooks, except perhaps just to set custom flags for the
> service to inspect.
>
> It's not the same as `new_record?` because `new_record?` is only true before
> record is saved, not after save. I'm thinking `newly_created?` or
> `just_created?` name. Calling it `created?` would be too ambiguous and
> higher chance to clash with similarly named method by application developers
> in their own code.
>
> Essentially `new_record?` to `newly_created?` is the same as
> `marked_for_destruction?` is to `destroyed?`, or as `changes` is to
> `previous_changes`.
>
> In my app I've implemented the code like this:
>
>> def newly_created?
>> id_changes = previous_changes['id']
>> id_changes && id_changes.last && !id_changes.first
>> end
Not entirely sure exactly what you mean by newly created. Do you mean
not updated since created (in which case you could compare created_at
and updated_at) or only just recently created (in which case you could
compare created_at to time now) or created within the current request
(in which case just remember in code that you have just created it) or
something else.
Colin
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLtJdQMPAW%2B65LJONxA0w5RPtyYiRrqTeF%3DrpHvGgpY%3DAg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAG_K1Sbap2TYkMhPUc%2BNMqTZh_4%3D9Tat_-asfpAkOUCpgmjNNQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment