Forum: Ruby on Rails Overriding the initializer

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fcdafe495dccc04d27f6dbbcdf54aecc?d=identicon&s=25 Woei Shyang (generik)
on 2006-01-12 07:17
Hi,

A question that I have been thinking about is.. by the time the
initialize method is called, has the instance of the object already been
created?

I've been thinking of creating a class object that would only have one
given instance based on a given attribute (ie: a "Town" object, whereby
only 1 town can exist in the entire table with a particular postal code)
but to simplify things, I don't wish to have the need to have to check
for the existence of this object prior to invoking the constructor. What
I'm trying to do is to make it such that if the object already exists,
the existing one will be returned back to the caller instead.

I hope I have not been making it sound too complicated :)

Is it doable by simply assigning "self" to the existing value in the
initialize method for existing records?

Thanks.
C8a634a01a2c4508360874bff7fb1a7f?d=identicon&s=25 Kevin Olbrich (olbrich)
on 2006-01-12 07:31
You might be able to do some funky stuff with singletons, but it sounds
like you really just want to make sure your tables have unique data.

Easiest way is to prevent that data from being added in the first place.

Add something like...

validates_uniqueness_of :postal_code

... to your model and then if someone tries to add a duplicate record,
rails will stop them.

_Kevin
This topic is locked and can not be replied to.