简体   繁体   中英

Consecutive numbered values to records in Ruby on Rails according to sort by created_at

For a project my company is involved in, I need to forward some data according to their consecutive numbering according to their creation date(time). Some data is already stored.

The only way I found up to now is to set a similar value as the id column for a model in Ruby on Rails. These values are consecutive starting from 1 (to n , with n being the number of records in the table), according to the values of another column. I don't want to override the default id column, of course.

I just came up with the following code:

class User < ApplicationRecord
...
def id_2
  User.all.order(:created_at).index(self) + 1
end

But I sense that there can be some better way to this approach, even database-oriented.

Is there a more efficient implementation for this, instead of calling the whole contents of the table, as per the code?

如果您的数据库支持它,您可能应该简单地将列设置为auto_increment

add_column :table_name, :id_2, :integer, auto_increment: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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