내 레일 애플리케이션에 대한 uuid를 생성해야합니다. 내가 가진 옵션 (보석)은 무엇입니까? [복제]
이 질문에 이미 답변이 있습니다.
- Ruby 10 답변 에서 Guid 생성
Rails 3.0.20과 ruby 1.8.7을 사용합니다 (2011-06-30 패치 레벨 352).
GUID를 생성하는 가장 좋은 플러그인을 제안하십시오.
많은 옵션이 있으므로 추가 종속성을 추가하지 않고 SecureRandom
기본 제공되는 사용 을 권장합니다 .
SecureRandom.uuid #=> "1ca71cd6-08c4-4855-9381-2f41aeffe59c"
내가 제안하는 첫 번째 것은 루비와 레일 버전을 업그레이드하는 것입니다.
guid를 생성하는 아주 좋은 방법은 Ruby 모듈 인 SecureRandom 입니다. 쉽게 사용할 수 있습니다.
require 'securerandom'
guid = SecureRandom.hex(10) #or whatever value you want instead of 10
PostgreSQL을 사용하고 내장 된 uuid 열을 사용하여 열을 생성하는 유형에 따라 UUID를 자동 생성하는 것이 좋습니다.
Rails 3 마이그레이션의 예
execute <<-SQL CREATE TABLE some_items (id uuid PRIMARY KEY DEFAULT uuid_generate_v1()); SQL
Rails 4에서이 작업을 수행하는 더 좋은 방법 일 수 있습니다.
레일 3.X 및 4.X의 예제와 함께 UUID를 사용하기 위해 보안 랜덤 루비 표준 라이브러리를 사용하는 방법을 자세히 참조하십시오.
lib / usesguid.rb에 usesguid.rb 파일을 만들고 코드 아래에 붙여 넣습니다.
require 'securerandom'
module ActiveRecord
module Usesguid #:nodoc:
def self.append_features(base)
super
base.extend(ClassMethods)
end
module ClassMethods
def usesguid(options = {})
class_eval do
self.primary_key = options[:column] if options[:column]
after_initialize :create_id
def create_id
self.id ||= SecureRandom.uuid
end
end
end
end
end
end
ActiveRecord::Base.class_eval do
include ActiveRecord::Usesguid
end
config / application.rb에 다음 줄을 추가하여 파일을로드하십시오.
require File.dirname(__FILE__) + '/../lib/usesguid'
아래에 언급 된대로 UUID 기능에 대한 마이그레이션 스크립트를 작성하십시오.
class CreateUuidFunction < ActiveRecord::Migration
def self.up
execute "create or replace function uuid() returns uuid as 'uuid-ossp', 'uuid_generate_v1' volatile strict language C;"
end
def self.down
execute "drop function uuid();"
end
end
다음은 연락처 마이그레이션의 예이며 사용 방법입니다.
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts, id: false do |t|
t.column :id, :uuid, null:false
t.string :name
t.string :mobile_no
t.timestamps
end
end
end
모델에 사용하는 최종 방법
class Contact < ActiveRecord::Base
usesguid
end
이것은 Rails 애플리케이션에 대한 UUID를 구성하는 데 도움이됩니다.
이것은 Rails 3.0, 3.1, 3.2 및 4.0에서도 유용 할 수 있습니다.
사용 중 문제가 있으면 알려주세요. 간단합니다!
Rails4의 다른 옵션은 여기
'programing tip' 카테고리의 다른 글
Python과 Numpy를 사용하여 r- 제곱을 어떻게 계산합니까? (0) | 2020.09.23 |
---|---|
Mac 사용자 및 경고 : Nokogiri는 LibXML 버전 2.7.8에 대해 빌드되었지만 2.7.3을 동적으로로드했습니다. (0) | 2020.09.23 |
snackBar의 레이아웃을 사용자 지정하는 방법은 무엇입니까? (0) | 2020.09.23 |
액체 템플릿 태그를 이스케이프하는 방법? (0) | 2020.09.23 |
Google Maps v3 fitBounds () 단일 마커에 대해 너무 가깝게 확대 (0) | 2020.09.23 |