For this requirement has_manyhas the option uniq:
class User < ActiveRecord::Base
has_many :favorites
has_many :artists, :through => :favorites, :uniq => true
end
class Artist < ActiveRecord::Base
has_many :favorites
has_many :users, :through => :favorites, :uniq => true
end
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :artist
end
Using:
@users = User.find_all_by_age(26, :include => :artists)
@users.each do |user|
user.artists
end
Change 1
.
1-:
Artist.all(:joins => :users, :group => :id,
:conditions => ["users.age = ?", 26])
2-
Artist.all(:joins => :users, :select => "DISTINCT artists.*",
:conditions => ["users.age = ?", 26]))