2017-03-22 2 views
0

sqlite3にはuuidの処理がないので、私はそれを自分で生成しようとしました。sqlite3のrails5のidモデルのlambda uuid generator

多くの他の記事はこれに私を導いた:実際には罰金あなたがUser.create ...を行う際idフィールドにデフォルトのランダムなUUIDを生成します

create_table :users, id: false do |t| 
    t.string :id, :primary_key => true, null: false, default: -> { "(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))" } 
    ... 
end 

を。
しかし、あなたは私がNew Userリンクを押すと(デフォルトはビューを生成を経由して)実際に私のコントローラで私の場合である、User.newを行うとき、私は持っている:new_user_lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))

  • とにも:私のフォームのid値で

    • フォームのオプションをform_for @user, html: {id: "new_user"}として修正すると、フォームを送信するとhttp://localhost:3000/accounts/lower(hex(randomblob(4)))%20%7C%7C%20'-'%20%7C%7C%20lower(hex(randomblob(2)))%20%7C%7C%20'-4'%20%7C%7C%20substr(lower(hex(randomblob(2))),2)%20%7C%7C%20'-'%20%7C%7C%20substr('89ab',abs(random())%20%25%204%20+%201,%201)%20%7C%7C%20substr(lower(hex(randomblob(2))),2)%20%7C%7C%20'-'%20%7C%7C%20lower(hex(randomblob(6)))にリダイレクトされます。
      User.newで行われた場合は、フィールドidの値と思われます。

    だから私は、それがSecureRandomまたは類似のものと同じように、newを介して作成されたときにidフィールドのデフォルト値を生成する方法があるかどうかを知りたいです。

  • 答えて

    1

    ERF、解決策は、実際にはかなり簡単だった:私のapp/models/application_record.rb

    :私はobvouisly定義を保持していない

    • :同じような状況を満たすことが人々のために

      class ApplicationRecord < ActiveRecord::Base 
          self.abstract_class = true 
      
          after_initialize :generate_uuid 
      
          protected 
          def generate_uuid 
          self.id = SecureRandom.uuid unless self.id 
          end 
      end 
      

      idフィールド(t.string :id, default: -> { "(lower..."})の既定値の

    • idのデフォルトセットのタイプを:stringcreate_table :users, id: :string do |t|)に変更しました。
    関連する問題