loading words...

Apr 05, 2019 18:01:52

My draft

by @swizecteller | 221 words | 🐣 | 116💌

Swizec Teller

Current day streak: 0🐣
Total posts: 116💌
Total words: 32303 (129 pages 📄)

Here's a fun thing I learned today about Rails.

Rails has a find_or_create_by method. It helps you create unique DB models based on params.


First you find by whatever and if nothing is found, you create the model.

It's not quite as good as native Postgres stuff but works well enough most of the time. I use it a lot.

appointment = SalesAppointment.find_or_create_by!(

payer_info: self,

sales_rep: sales_rep,

appointment_at: appointment_at,

scheduled_at: scheduled_at

)


This method comes with a hidden magic trick 👉 you can add some code that only runs when the returned model is new.

If you want to run followup code on creation, but not on find, this is a great approach.


appointment = SalesAppointment.find_or_create_by!(

payer_info: self,

sales_rep: sales_rep,

appointment_at: appointment_at,

scheduled_at: scheduled_at

) do |appointment|

# creation followup code

end 


Pretty cool right? Yes.

You know what's not cool? The object you get into that block has all the right properties. All of them.

Except one ...

... there is no id.


appointment = SalesAppointment.find_or_create_by!(

payer_info: self,

sales_rep: sales_rep,

appointment_at: appointment_at,

scheduled_at: scheduled_at

) do |appointment|

# creation followup code

puts appointment.id # nil

end



And that right there is 2 hours of my life I'm never getting back.

Originally published at twitter.com

contact: email - twitter / Terms / Privacy