6b70a197d345a129a9ebc902dcebd308

I actually wanted somethin like:

has_many :autos, :through => :dealers

But the it complains:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'dealers.user_id' in 'where clause': SELECT `autos`.* FROM `autos` INNER JOIN `dealers` ON (`autos`.`dealer_id`=`dealers`.`id`) WHERE ((`dealers`.`user_id` = 1))

Thanks in advance!

class User < ActiveRecord::Base
  acts_as_authentic
  has_many :dealers_users
  has_many :dealers, :through => :dealers_users, :include => [:autos]
  has_many :autos, :class_name => 'Auto', :finder_sql =>
    'SELECT autos.* FROM autos
    WHERE autos.dealer_id IN (#{dealers.map(&:id).join(", ")})'

end

Refactorings

No refactoring yet !

53be54e5db4dc58e4980db5a8255621b

Harold Giménez

September 23, 2009, September 23, 2009 16:45, permalink

No rating. Login to rate!
C1b8493ace80fcca7a8ec19e96487cee

Brendan

December 31, 2009, December 31, 2009 16:36, permalink

No rating. Login to rate!

I believe this sql query will work for you. Using '... IN (1, 2, 3)' is actually pretty expensive too so this would perform better. That said there is probably a much better way yo handle this in ruby without any custom queries at all. I included a method that may work. I did not test any of this code or anything... hope I helped!

class User < ActiveRecord::Base
  acts_as_authentic
  has_many :dealers_users
  has_many :dealers, :through => :dealers_users, :include => [:autos]
  has_many :autos, :class_name => 'Auto', :finder_sql =>
    'SELECT autos.* FROM autos
    JOIN dealers_users ON dealers_users.dealer_id = autos.dealer_id
    WHERE dealers_users.user_id = #{id} 

    ***************

    def autos
        a = Array.new
        dealers.each do |d|
            a = a + d.autos
        end
        a
    end

end

Your refactoring





Format Copy from initial code

or Cancel