在第一次误解了这个问题之后,我会再试一次。
You are looking for a way to have an issue 'counter' (to simulate an id) that is specific to a company_id. Although @deivid was on the right track, relying on issues.count
will only work if you can guarantee that a company never makes more than one request at a time. This will generally be the case, but is not guaranteed and shouldn't be used alone as the core logic behind this counter.
You'll need to add a unique constraint/index to your issues
table - this will ensure that counter can't be duplicated:
add_index :issues, [:issue_id, :company_id], :unique => true
Adding a :uniqueness
constraint in the model will only mitigate the problem somewhat by making the window for the race condition smaller, but it can't guarantee uniqueness completely.
Note that in the event of a constraint violation in the DB, ActiveRecord can't recover from it within the transaction. You can try rescuing ActiveRecord::RecordNotUnique
, recreating the issue
(or just regenerating the issue_id
using a fresh count
) and saving again.