简体   繁体   English

在为模型导轨创建对象之前获取下一个对象ID

[英]Get the next Object Id before create the object for a Model Rails

I have a Model I need to get the next record id which is going to be create before create that object in my model like: 我有一个Model我需要获取下一个记录ID,该记录ID将在模型中创建该对象之前创建:

MyModel.last.id #=> 10
MyModel.last.destroy
MyModel.last.id #=> 9, so (Model.last.id + 1) would be 10... but...
MyModel.create  #=> 11, my next id was actually 11

Can you please suggest a better way to solve my problem? 您能否提出解决我的问题的更好方法?

Thanks 谢谢

You are looking for the table's AUTO_INCREMENT value. 您正在寻找表的AUTO_INCREMENT值。 MySQL stores such metadata in the INFORMATION_SCHEMA database. MySQL将此类元数据存储在INFORMATION_SCHEMA数据库中。 The AUTO_INCREMENT values can be found in the TABLES table. 可以在TABLES表中找到AUTO_INCREMENT值。 The table contains one entry for each database and table. 该表为每个数据库和表包含一个条目。

I don't think Rails or the MySQL gem provide any built-in method for fetching it. 我认为Rails或MySQL gem不提供任何内置方法来获取它。

I have used something like this in one of my previous projects: 我在以前的一个项目中使用过类似的方法:

# config/initializers/auto_increment.rb

module AutoIncrement
  def auto_increment_value
    connection.execute(<<-SQL.squish).first[0]
      SELECT `AUTO_INCREMENT`
        FROM `INFORMATION_SCHEMA`.`TABLES`
       WHERE `TABLE_SCHEMA` = '#{connection.current_database}'
         AND `TABLE_NAME` = '#{table_name}'
    SQL
  end
end

ActiveRecord::Base.extend(AutoIncrement)

You can then execute: 然后,您可以执行:

MyModel.auto_increment_value

and it will return the current value for the table's AUTO_INCREMENT value, eg 11 . 并将返回表的AUTO_INCREMENT值的当前值,例如11

Note that it is not safe to use that value as an explicit ID for your record. 请注意,使用该值作为记录的显式ID是不安全的。 You should let MySQL handle the assignment of new IDs – that's what AUTO_INCREMENT is for. 您应该让MySQL处理新ID的分配-这就是AUTO_INCREMENT的目的。

Why worry about the id? 为什么要担心身份证? If you have some other reasons for a contiguous number, use another field and do some select max on a before_create. 如果您有其他原因需要连续的数字,请使用另一个字段,并在before_create上选择max。

FWIW, MySQL, and Mariadb auto increment only resets on a database restart, which avoids race situations. FWIW,MySQL和Mariadb自动增量仅在数据库重新启动时重置,从而避免了竞争情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM