如何使用Ruby on Rails从不同模型的数组中提取唯一的关联实例?
- 内容介绍
- 文章标签
- 相关推荐
本文共计401个文字,预计阅读时间需要2分钟。
为另一个子集找到多个唯一关联模型的推荐方法有哪些?例如,针对一部分用户,确定他们所喜欢的特定艺术家的模型。一种方法是:从数据库中获取用户信息,然后遍历他们所有的查询和收藏夹。
一种方法是从数据库中获取用户,然后迭代它们所有查询收藏夹并构建一个独特的数组,但这似乎效率低且速度慢.
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, :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]))
本文共计401个文字,预计阅读时间需要2分钟。
为另一个子集找到多个唯一关联模型的推荐方法有哪些?例如,针对一部分用户,确定他们所喜欢的特定艺术家的模型。一种方法是:从数据库中获取用户信息,然后遍历他们所有的查询和收藏夹。
一种方法是从数据库中获取用户,然后迭代它们所有查询收藏夹并构建一个独特的数组,但这似乎效率低且速度慢.
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, :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]))

