3 ms·
Rails has support for database transactions, but depending on what you want to do, things won't be magically transactional all by themselves (that said, it's re
by ryanbrunner 6y ago
Rails has support for database transactions, but depending on what you want to do, things won't be magically transactional all by themselves (that said, it's really just a matter of wrapping transactional code in a block).
There are a couple of footguns in Rails involving transactions - by default, validating uniqueness of a column in Rails will be done at the app layer which is prone to race conditions, and with a typical CRUD model for an application, there's nothing in particular preventing overwrites of model data if say, a field was present on a form and two people were editing it, even if the "later" editor made no changes to that particular field.
When multiple systems and things other than databases (or multiple databases) are involved, you're generally on your own as well.
- pbowyer 6y agoIt's important to say that these footguns are not exclusive to Rails. I don't know a single web framework which avoids them - if it exists I'd like to know so I can learn how they do it.
- RickSullivan 6y agoElixir's Ecto has the best solution to this problem in my experience--it doesn't do database validations on things like uniqueness, but provides easy error handling when constraints are hit. It encourages you to write validations for things that don't need to hit the DB, but actually uses the DB for handling constraints, since it's the real source of truth for data consistency.
- andi999 6y agoThanks. So typical CRUD applications usually run on luck? (or on not beeing unlucky if the average number of request per hour is not so high).
- msbarnett 6y agoNot really? Most CRUD applications go the one extra step of putting a uniqueness constraint on the column instead of just relying on the app layer validation, and comparing hidden time stamps on the form if multiple people might edit the same row simultaneously. It’s exceedingly straightforward. Did you really think thousands of web apps up to and including GitHub and shopify were squeaking by on blind luck? If basic database transactions and integrity weren’t doable in Rails, that’d have had to have been fixed years ago.
- andi999 6y agoAny reference how this is best done with rails?
- msbarnett 6y agoDepends on what you mean by “this”, I suppose. Most of your basic questions are covered by the starter Rails Guide for ActiveRecord, eg) transactions, validations, how to add a uniqueness constraint to the DB in a migration https://guides.rubyonrails.org/active_record_basics.html https://guides.rubyonrails.org/active_record_basics.html The ActiveRecord Queries guide also covers some mechanisms for handling row-level write contention https://guides.rubyonrails.org/active_record_querying.html#locking-records-for-update https://guides.rubyonrails.org/active_record_querying.html#l...