DEV Community

Discussion on: Battling RecordNotUnique in Rails

Collapse
 
djuber profile image
Daniel Uber • Edited

Awesome discussion of the trade-offs here. One note:

I needed to know how the create_or_find_by went. Did the record just get inserted? I don't know of a way to tell.

AR models expose a previously_new_record? that's true when an object was new? (not yet persisted) before the last update. If you found (rather than created) the object you'd see previously_new_record? respond false, if you created it would be true.

$ rails --version
Rails 6.1.3.1
$ rails new bloog
$ cd rails
$ rails g model name name:string{30}:uniq
$ rails db:prepare
$ rails console
irb(main):001:0> n1 = Name.create_or_find_by(name: "John")
irb(main):002:0> n2 = Name.create_or_find_by(name: "John")
irb(main):003:0> n1.previously_new_record?
=> true
irb(main):004:0> n2.previously_new_record?
=> false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jakswa profile image
Jake Swanson

Oh wow! That method is brand new 🆕 as of Rails 6.1! Thanks for the heads up. I think that'll be killer for new repos (or my existing repos, once I can get them upgraded 😅).