ruby-on-rails – 从另一个模型的数组中检索唯一的关联模型

为另一个模型的子集找到多个唯一关联模型的推荐方法是什么?例如,对于一部分用户,确定他们所青睐的独特艺术家模型.

一种方法是从数据库中获取用户,然后迭代它们所有查询收藏夹并构建一个独特的数组,但这似乎效率低且速度慢.

class User < ActiveRecord::Base
  has_many :favorites
end

class Artist < ActiveRecord::Base
  has_many :favorites
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :artist
end

@users = User.find_by_age(26)
# then determine unique favorited artists for this subset of users.

解决方法

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,: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.*",26]))

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...