Getting unique related models from an array of another model

What is the recommended approach for finding several unique related models for a subset of another model? As an example, for a subset of users, identify the unique artist models that they prefer.

One approach is to grab users from the database and then repeat them all the queries for the elite and create a unique array, but this seems rather inefficient and slow.

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.
+3
source share
1 answer

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:

# 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

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]))
+7

Source: https://habr.com/ru/post/1760855/


All Articles