class Activity < ActiveRecord::Base
has_and_belongs_to_many :products
has_and_belongs_to_many :articles
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :activities
end
class Article < ActiveRecord::Base
has_and_belongs_to_many :activities
def products
products = []
self.activities.each do |a|
a.products.each do |p|
products << p unless products.include?(p)
end
end
products.sort_by { |m| m.name }
end
end
Refactorings
No refactoring yet !
steved
March 25, 2010, March 25, 2010 18:26, permalink
def products activities.map(&:products).flatten.uniq.sort_by(&:name) end
vitaly
May 27, 2010, May 27, 2010 02:17, permalink
first of all, has_and_belongs_to_many is not recommended to use.
better use has_many :though
but in this code we (I'm 90% sure) can use :though to do just what you need
class Activity < ActiveRecord::Base has_and_belongs_to_many :products has_and_belongs_to_many :articles end class Product < ActiveRecord::Base has_and_belongs_to_many :activities end class Article < ActiveRecord::Base has_and_belongs_to_many :activities has_many :products, :though => :activities end
Using: Article.first.products