Tagged: has_many

ActiveRecord has_many through multiple models

More than a few times now I've run into a situation where I really need to be able to relate one object to another through multiple tables - basically use 'has_many' twice.

Here's an example set of objects where a user can have many products but to get to the products you have to first go through associations and then through companies. 'user.companies' is straight forward ActiveRecord but 'user.companies.products' won't give you what you need.

class User < ActiveRecord::Base has_many :associations has_many :companies, :through => :associations end

class Association < ActiveRecord::Base belongs_to :user belongs_to :company end

class Company < ActiveRecord::Base has_many :associations has_many :users, :through => :associations has_many :products end

class Product < ActiveRecord::Base belongs_to :company end

What I really want to do is setup an efficient query that bypasses the companies table. The associations table and the product...

Continue Reading →