Upgrade to Pro — share decks privately, control downloads, hide ads and more …

What's wrong with ActiveRecord?

Rostislav Zhuravsky
March 15, 2021
27

What's wrong with ActiveRecord?

Rostislav Zhuravsky

March 15, 2021
Tweet

Transcript

  1. Rails way(a.k.a pain in the ass) solutions • adding a

    new flag attribute • save(validate: false) • update_column • connection.execute(raw_sql)
  2. Well-known solutions • Form objects - https://thoughtbot.com/blog/activemodel-form-objects • ActiveModel-based validations

    • Dry-validation https://dry-rb.org/gems/dry-validation/1.5/ https://www.youtube.com/watch?v=nOUPIa7tWpA More about each concept here - https://gist.github.com/woarewe/1c4895378fac77e6a39e4a8fc139ecc9#valida tors
  3. Common uses cases • Post-processing: notifications, enquing jobs, No-SQL and

    MQ sync(elasticsearch, RabbitMQ, Kafka) • Pre-processing: deserialize data from forms, coerce types • Trigger other triggers - touch, touch, touch
  4. Why is it the worst practice? • Unobvious and implicit

    behavior • Forces you to use several interfaces to communicate with DB, basically, if you see a code with update_column you can’t understand if it’s for skipping callbacks or optimization, or etc. • Production scripts are super dangerous • Should I mention testing there? • The concurrency control(nested transactions, locks) is getting super hard to maintain
  5. Data setup • There are 100 users • Every user

    has 10 posts • Every post has 20 comments • Every comment has 10 reactions
  6. Our task is to save a bunch of data. For

    instance: import CSV, API sync or consuming MQ
  7. Imagine, than you sync data and a part of it

    is already persisted and a part is new
  8. Common raw SQL won’t help! You are able to set

    the same value for several rows but what to do if you need to set unique value for every row?
  9. Summary • N+1: it’s not only about selects • The

    rails-way is a bullshit • Models without validations and callbacks • Preload data you need • Easy is not simple • Understanding tools that you use gives a huge advantage