4203bf83f438804dde849b48de826158

Using: Article.first.products

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 !

D41d8cd98f00b204e9800998ecf8427e

steved

March 25, 2010, March 25, 2010 18:26, permalink

3 ratings. Login to rate!
def products
  activities.map(&:products).flatten.uniq.sort_by(&:name)
end
996b64c2708771eb4f0c479e0d3a0646

vitaly

May 27, 2010, May 27, 2010 02:17, permalink

No rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel