Using named_scope with finder_sql

Named scopes and associations using finder_sql don’t mix. And there really is no solution to that problem. Rails has no way to inject conditions into raw SQL that may or may not follow Active Record conventions. But, the need may come up that you want to return a set of records from an association driven by finder_sql, but also have the freedom to chain that result set with other named_scopes in your app. Here’s how I do it:

Let’s pretend that this query needs to be expressed in SQL:

class Owner < ActiveRecord::Base
  has_many :things, :finder_sql=>'SELECT things.id FROM things where    (things.owner_id = #{id}) '
end

So this will return a collection of ActiveRecord Thing objects as an array, but you can’t call any other named_scopes on that array. Here’s the way around that:

class ThingsController < ApplicationController

  def index
    @things = Thing.scoped({:conditions => {:id => @owner.things.map(&:id)}})
  end
end

So, Thing.scoped will return a named_scope so you can then take advantage of both a custom association driven by finder_sql and still utilize named_scopes. This solution isn’t perfect, but it just may get you out of a jam sometime.

Post a Comment

Your email is never shared. Required fields are marked *

*
*