在rails 5中创建之前,为每个模型添加唯一ID

时间:2017-10-06 17:18:07

标签: ruby-on-rails activerecord

var pattern = /^[N]/gi;
if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == 'Not Aged'){1}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '1-30'){2}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '31-60'){3}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '61-90'){4}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '91-120'){5} 
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '121-150'){6}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '151-180'){7}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '181-210'){8}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '211-240'){9}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '241-270'){10} 
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '271-300'){11}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '331-365'){12}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '331-365'){13}
else if (dimension["Group1"]["CATEGORY_DESCRIPTION"] == '366+'){14}   
else {99}

在我的控制器/关注/ jhm_unique_id_gen_helper.rb中,我有:

Rails 5.1
Ruby 2.4.1
mysql

典型的迁移(以用户为例)包含以下内容:

require 'time'

module JHMUniqueIdGenHelper

  def self.included(base)
    base.primary_key = 'id'
    base.before_create :assign_id
  end

  private
  def assign_id
    time = Time.now
    self.id = "#{time.to_i}#{time.usec}" if self.id.blank?
  end

end

在我的app / controllers / application_controller.rb中,我有:

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table :users, id: false do |t|
      t.string :id, limit: 16, primary: true, null: false

还有什么我需要做的,以确保在创建之前生成并添加到模型中的id?

0 个答案:

没有答案