Skip to content

Instantly share code, notes, and snippets.

@lukeredpath
Created February 20, 2009 17:55

Revisions

  1. lukeredpath created this gist Feb 20, 2009.
    21 changes: 21 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    module RailsExtensions
    module HasManyThroughWithScope
    def has_many_with_scope(association, options={})
    if (through = options[:through]) && (scope = options.delete(:scope))
    if conditions = through.to_s.classify.constantize.send(scope).proxy_options[:conditions]
    scope_conditions = conditions.inject({}) do |scope_conditions, (key, value)|
    scope_conditions["#{through}.#{key}"] = value
    scope_conditions
    end
    options[:conditions] = (options[:conditions] || {}).merge(scope_conditions)
    end
    end
    has_many_without_scope(association, options)
    end
    end
    end

    ActiveRecord::Base.extend(RailsExtensions::HasManyThroughWithScope)
    ActiveRecord::Base.metaclass.instance_eval do
    alias_method_chain :has_many, :scope
    end