How do I get ActiveRecord to show the next id (last + 1) in Ruby on Rails?

前端 未结 13 1276
臣服心动
臣服心动 2020-12-05 06:33

Is there a compact way with ActiveRecord to query for what id it\'s going to use next if an object was going to be persisted to the database? In SQL, a query like this would

13条回答
  •  隐瞒了意图╮
    2020-12-05 07:00

    There seems to be need of a answer here that removes the race conditions, and addresses the actual problem of pre-providing unique identifiers.

    To solve the problem you maintain a second model, which serves unique ID's for the primary model. This way you don't have any race condition.

    If you need to make these ID's secure you should hash them with SHA256 (or SHA512) and store the hash as an indexed column on identifier model when they are generated.

    They can then be associated and validated when used on the primary model. If you don't hash them you still associate them, to provide validation.

    I'll post some example code a bit later.

提交回复
热议问题