这个
has_many
关联有一个名为
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
用法:
# if you are expecting an array of users, then use find_all instead of find_
@users = User.find_all_by_age(26, :include => :artists)
@users.each do |user|
user.artists # unique artists
end
编辑1
解决方案1-:组
Artist.all(:joins => :users, :group => :id,
:conditions => ["users.age = ?", 26])
解决方案2-选择DISTINCT
Artist.all(:joins => :users, :select => "DISTINCT artists.*",
:conditions => ["users.age = ?", 26]))