ndemoreau
ndemoreau

Reputation: 3869

rails polymorphic many-to-many association

I have these models:

class Company < ActiveRecord::Base
  has_many :categorizings, as: :categorizable
  has_many :categories, :through => :categorizings

class Categorizing < ActiveRecord::Base
  belongs_to :category
  belongs_to :categorizable, polymorphic: true

class Category < ActiveRecord::Base
  has_many :categorizings
  has_many :categorizables, through: :categorizings

How can I get all the companies having a specific category?

I tried

Category.find_by_name("fff").companies

plus a lot of other solutions but couldn't get it working

Thx!

Upvotes: 0

Views: 282

Answers (1)

Mike Szyndel
Mike Szyndel

Reputation: 10593

You could do the following

Category.first.categorizables.where(categorizable_type: 'Company')

that would select all the Companies associated with Category using your relationship schema.

Also read some about has_many :through association because I think you don't quite get it http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Upvotes: 1

Related Questions