Forum: Ruby on Rails has_many_through with conditions on another table (:joins)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Michael S. (Guest)
on 2008-10-07 04:12
(Received via mailing list)
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?
Michael S. (Guest)
on 2008-10-07 04:20
(Received via mailing list)
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.
Michael S. (Guest)
on 2008-10-07 06:40
(Received via mailing list)
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.
This topic is locked and can not be replied to.