CrudVision - Lisa Seelye

January 2, 2008

Followup to My First Patch

Filed under: activerecord, open source, oracle, rails, snippet, sql — Lisa Seelye @ 5:50 pm

In reference to the post about My First Patch to the Rails trac I mentioned in the edit of the post that I emailed the maintainer. There’s been no response, unfortunately.

So I’ll post the patch here so it’ll get a bit more visibility and hopefully Oracle users can find it helpful in speeding up rake db:migrate on Oracle systems with a lot of indicies.

Patch to speed up Rails’s OracleAdapter#indexes method

December 8, 2007

Rails has_many gotcha

Filed under: activerecord, crud, rails, ruby, sql, work — Lisa Seelye @ 2:39 pm

With Rails there's a useful set of callback methods that can be used within model classes. They include after_create, before_validation and the one I want to talk about after_initialize.

A lot of cool things can be done with after_initialize, especially if one uses the database as a means to store meta-data about a model. Use the after_initialize method to transform your models with Ruby after they're fethced from the database. Consider the following User model definition:

RUBY:
  1. class User <ActiveRecord::Base
  2.   has_many :memberships, :order => "memberships.group_id, memberships.expires_at desc", :group => "group_id"
  3. end

It's pretty clear that with the :group => "group_id" that I want a unique set of Membership objects. That works well when I've already got a User and do user.memberships but not at all when I do User.find(:first, :include => :memberships); likely because of the way the join is set up and grouping on that may not be possible.

I still wanted to use eager loading so I thought that it would be an OK sacrifice to fetch all the Membership objects even if I wanted to pare it down after I initialize the User object (with eager loading). I defined:

RUBY:
  1. class User <ActiveRecord::Base
  2.  
  3.   def after_initialize
  4.     do stuff with @memberships instance varible
  5.   end
  6. end

Except it doesn't work. Quickly I found the following from active_record/base.rb (click link for source): right where it does the after_initialize callback! But it wasn't working for me. I needed to dig further.

Further research indicated that before the creation of the @memberships instance variable that would hold the collection of Membership objects the after_initialize callback was being fired off in the User model. Using after_initialize would not work due to the design of ActiveRecord. I'm still searching for an elegant way to work the way I want. I'll post again when I find it!

Powered by WordPress