-
Getting friendly_id to work!
- robert
- June 23rd, 2008
- 02:16:28 PM
If you have read Allyn’s post from a week ago, you would have noticed him saying:
“For example, our current application has a page that executes several hundred queries when it loads. Obviously this is absolutely horrible and will have to be fixed before it’s released.”
Well, this was exactly what I set off to do this morning! When we initially wrote the page we used Eager Loading to cut down on our queries, though for some reason it was not working!
I looked into it for quite some time with Kevin, and we came to the conclusion that the Friendly ID plugin that was causing all the trouble. For some reason, it wasn’t passing our ActiveRecord’s :include parameters.
After poking around int he code for a bit, we came up with a solution:
Line 127 has a method called “find_using_friendly_id” in the SluggableClassMethods module. This method was originally not passing on the options parameter, since it wasn’t calling ActiveRecord’s default “find” method. Instead it was returning the Slug class’s polymorphic association, e.g., “Slug.sluggable.” I reworked the method to get the Sluggable class type and then called the find method, to which I passed the options parameter! So, with a little tweaking, this method now works with :includes, :conditions, and all the other fun ActiveRecord find parameters.Here is the new find_using_friendly_id we worked up:
# Finds the record using only the friendly id. If it can't be found
# using the friendly id, then it returns false. If you pass in any
# argument other than an instance of String, then it also returns false.
def find_using_friendly_id(*args)
return false unless args.first.kind_of?(String)
slug = Slug.find_by_name_and_sluggable_type(args.first, self.to_s)
begin
# Get the class and pass our options
object_class = Module.const_get(slug.sluggable_type)
options = args.extract_options!
return object_class.find(slug.sluggable_id, options)
rescue # The class was bad, use the old slug way
return false if !slug
return false if !slug.sluggable
slug.sluggable.send(:finder_slug=, slug)
slug.sluggable
end
endHope this helps someone out there!
Comments
Poop?
BrightMix sees Dark Knight @ IMAX
Robert's victory pose
Trick Starbursts
Genius man, genius. I was running into a similar problem this morning and this cleared it right up. Thanks!