Has_many_through with conditions on another table (:joins)


#1

Hi,

I have an class that looks like this:

class Section < ActiveRecord::Base
belongs_to :offering, :foreign_key => :parent_id
has_many :memberships, :as => :member_of
has_many :students, :through => :memberships, :source => :user,
:joins => “inner join roles onmemberships.role_id =
roles.id”, :conditions =>“roles.name = ‘Student’”
end

This doesn’t work, though, because :joins isn’t an allowed key. From
associations.rb:

    def create_has_and_belongs_to_many_reflection(association_id,

options, &extension)
options.assert_valid_keys(
:class_name, :table_name, :join_table, :foreign_key,
:association_foreign_key,
:select, :conditions, :include, :order, :group, :limit,
:offset,
:uniq,
:finder_sql, :delete_sql, :insert_sql,
:before_add, :after_add, :before_remove, :after_remove,
:extend, :readonly,
:validate
)

I added :joins to the list of allowed keys, and it made my tests pass,
but I want to check that I’m not doing something silly. Is there a
particular reason that :joins isn’t an allowed key for
has_many :through?


#2

Correction: I made the change to :create_has_many_reflection

If there is no reason not to allow the :join keyword, what is the best
way to make the change? I’d prefer not to freeze Rails, but I’m
having a lot of trouble targeting just this method with a plugin.


#3

I was able to get this to work by using :include => {:memberships
=> :role} but that’s far from ideal as Ruby will build a lot of
objects I don’t need, and waste a significant amount of time and
memory doing it.