【问题标题】:Retrieving unique associated models from an array of another model从另一个模型的数组中检索唯一的关联模型
【发布时间】:2011-04-01 22:45:36
【问题描述】:

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

一种方法是从数据库中获取用户,然后遍历所有用户以查找收藏夹并构建唯一数组,但这似乎效率低下且速度慢。

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.

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations


    【解决方案1】:

    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- :group

    Artist.all(:joins => :users, :group => :id, 
      :conditions => ["users.age = ?", 26])
    

    解决方案 2- SELECT DISTINCT

    Artist.all(:joins => :users, :select => "DISTINCT artists.*", 
      :conditions => ["users.age = ?", 26]))
    

    【讨论】:

    • 这将为您提供每个用户的唯一艺术家数组,而不是所有用户的唯一列表。我对么?我希望最终的艺术家数组是独一无二的
    • 谢谢!我相信这应该可以完美运行,现在就试一试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多