On Thu, Feb 9, 2012 at 7:07 AM, Hassan Schroeder wrote:
On Wed, Feb 8, 2012 at 8:54 PM, Bob Smith wrote:

What I am trying to do is have a *unique value* set in each new record
See: http://rubygems.org/gems/uuid
Indeed.

And maybe better to not mess with the `def initialize`, but use the
`after_initialize` function that is provided by Rails. I did it like this.


../lib/uuid_helper.rb

require 'uuidtools'

module UUIDHelper
extend ActiveSupport::Concern

included do
after_initialize :set_uuid
def set_uuid
unless uuid # Note 1 below
self.uuid = UUIDTools::UUID.random_create.to_s
end
end
end
end

../app/model/person.rb

class Person < ActiveRecord::Base

# UUID
include UUIDHelper
...
end

Note 1:
Be careful, it is a little tricky to _only_ set the value of the uuid
when it is not yet present, otherwise reading back the value
from the database will build a new instance of Person with a
new random uuid. The code above is well tested and works.

Maybe you will also need to add ../lib to your default load path.
In config/application.rb

# Custom directories with classes and modules you want to be
autoloadable.
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]


HTH,

Peter

*** Available for a new project ***

Peter Vandenabeele
http://twitter.com/peter_v
http://rails.vandenabeele.com
http://coderwall.com/peter_v

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 12 of 15 | next ›
Discussion Overview
grouprubyonrails-talk @
categoriesrubyonrails
postedFeb 8, '12 at 7:13a
activeFeb 26, '12 at 9:52p
posts15
users7
websiterubyonrails.org
irc#RubyOnRails

People

Translate

site design / logo © 2022 Grokbase