Archive for the ‘activerecord’ Category

Extending ActiveRecord::Base.find with new options

Monday, March 5th, 2007

I’m working on a new full text search index Ruby on Rails plugin that works completely in the database. This makes it possible to:

  • combine a full text query with other more structured criteria,
  • using LIMITs to do pagination,
  • sorting,
  • joins,
  • etc.

Right now you can do:

class Author < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :author
acts_as_full_text_searchable
end
@jon = Author.create!(:name => ‘Jon Tirsen’)
@post = @jon.posts.create!(
:title => ‘Hitta, the full text search plugin’,
:body => ‘Blah blah blah’)

@jon.posts.find(:all, :full_text_search => ‘hitta’)

So I’ve managed to extend ActiveRecord::Base.find to support a new option called :full_text_search.

Problem is:
I can’t seem to get alias_method_chain to work on ActiveRecord::Base.find.

It seems to be something about it being a class method or whatever. I’ve tried (anyone that has ever written an acts_as-plugin should be familiar with this terminology):

  • Putting the call to alias_method_chain in ClassMethods.
  • Putting the call to alias_method_chain in SingletonMethods.
  • ActiveRecord::Base.send(:alias_method_chain, ...).
  • And finally out of desperation I put the call into InstanceMethods.

Here’s the code:
http://hitta.googlecode.com/svn/trunk/hitta/lib/acts_as_full_text_searchable.rb

Wouldn’t it be so cool if Rails plugins could add options to find that gets expanded into for example :conditions and :joins?

Please help!

(Btw, “hitta” means “to find” in swedish.)