Considering the following
:company has_many :issues #ticket tracking example
I’d like to have routing such that any user in the company can go to /issues/:id (which is simple enough when using the default id column).
However, i’d like instead to have an issue id specific to the company (so each company would have their own issue 1, 2, 3 etc that isn’t unique (and wouldn’t use the internal id).
Is there any better way than calculating an id based on the last number in the db in the create and update actions in IssueController for that company id? (I can think of various issues here with race conditions when multiple records are being updated/created per company).
Thanks in advance!
I would take the
issue_idhandling down to the model level. You can use a before_validation callback to set theissue_id. This alone, even though thesavecall is wrapped in a transaction, won’t prevent race conditions. You have to further ensure the uniqueness of the couple[ :company_id, :issue_id ]by adding a index/unique constraint to yourissuestable, as suggested by @PinnyM. So something like thisand inside a migration:
And you could grab the correct issue in the controller like you said:
Note that this doesn’t provide a way to recover from a constraint violation exception in case that actually happened. See @PinnyM answer for a suggestion on how to handle this.
Hope this helps.