[Rails] Active Record Question
Tom Ward
tom.ward at gmail.com
Wed Nov 10 11:27:30 GMT 2004
I'm new to both Ruby and Rails, so someone may well have a better
suggestion, but here's how I'd do this:-
module UUIDHelper
def before_create()
sql = "SELECT UUID()"
record = connection.select_one(sql, " #{name} UUID generated")
self.id = record['UUID()']
end
end
class ModelClass < ActiveRecord::Base
include UUIDHelper
end
Including the module should add the methods defined as a mixin, while
before_create is a callback method called before creation (a bit
cleaner than overriding create).
http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Hope this is helpful,
Tom Ward
On Tue, 9 Nov 2004 23:05:51 -0800, Aled Davies <awd at well.com> wrote:
> (I posted this at ruby-forum, but I figured that I should also try
> here):
>
> I'm new to Ruby and Rails and am evaluating using Ruby on Rails as the
> framework for an asset management project I'm working on and have run
> into an issue with Active Record that I'm wondering if there is anyway
> around.
>
> The issue is this, one of the requirements I have is that all asset
> primary keys must be UUIDs. MySQL 4.1 allows the generation of UUIDs
> using 'SELECT UUID()' so to implement support for using a UUID as a
> primary key, I added the following methods to my model class:
>
> Code:
>
> def uuid()
> sql = "SELECT UUID()"
> record = connection.select_one(sql, " #{name} UUID generated")
> return record['UUID()']
> end
>
> # Override create to insert the identifier prior to creation.
> def create
> self.id = uuid();
> super
> end
>
> As this code will be common to all models in the application I figured
> that I could move this into a super-class (that extends
> ActiveRecord::Base) that sub-classes can extend to get this
> functionality for free. The problem is that ActiveRecord tries apply
> the single-table inheritance rule to the model and tries to insert a
> type in the table (which fails because it isn't in the model).
>
> And so the question is this. Is there anyway of having a custom
> super-class for your models which won't trigger the single-table
> inheritance rule ?
>
> (while I realize that I can just add a 'type' field to the database, it
> seems like the wrong thing to have to do in this case. I also tried
> using a Module, but this seemed not to work, but I suspect that was
> down to my newness with Ruby)
>
> Thanks
>
> Aled
>
> --
> Aled Davies <awd at well.com>
>
>
> _______________________________________________
> Rails mailing list
> Rails at lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
>
>
>
More information about the Rails
mailing list