ruby-on-rails – Rails3中的UUID

我正在尝试设置我的第一个Rails3项目,并且在早期,我遇到了uuidtools,我的UUIDHelper或者回调问题.我显然正在尝试使用UUID和(我认为)我按照 Ariejan de Vroom’s article中的描述进行了设置.我尝试使用UUID作为主键,也只是一个补充字段,但看起来UUIDHelper似乎是永远不会被召唤

我已经阅读过许多关于Rails3中回调和/或帮助器改变的提及,但我找不到任何可以告诉我如何调整的细节.这是我现在的设置(已经进行了几次迭代):

# migration
class CreateImages < ActiveRecord::Migration
  def self.up
    create_table :images do |t|
      t.string :uuid,:limit  => 36
      t.string :title
      t.text :description

      t.timestamps
    end
  end
  ...
end

# lib/uuid_helper.rb
require 'rubygems'
require 'uuidtools'

module UUIDHelper
  def before_create()
    self.uuid = UUID.timestamp_create.to_s
  end
end

# models/image.rb
class Image < ActiveRecord::Base
  include UUIDHelper

  ...
end

任何见解都会非常感激.

谢谢.

解决方法

你在Image模型中声明了另一个before_create方法吗?如果是这样,您将覆盖UUIDHelper模块中的那个.您需要以不同的方式声明回调,或者在图像模型的回调中调用super.

编辑:也许更改帮助器看起来像这样:

module UUIDHelper
  def self.included(base)
    base.class_eval do
      before_create :set_uuid

      def set_uuid
        self.uuid = UUID.timestamp_create.to_s
      end
    end
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...