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 !
Brendan
December 31, 2009, December 31, 2009 16:36, permalink
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
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!