Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails HABTM with polymorphic relationships

I have a table Category which can have many Businesses and Posts. And a Business/Post can have many Categories so I created a polymorphic tabled called CategoryRelationship to break up the many to many relationship.

Business model has these relationships:

  has_many :categories, through: :category_relationships, :source => :category_relationshipable, :source_type => 'Business'
  has_many :category_relationships

CategoryRelationship model has these relationships:

 attr_accessible :category_id, :category_relationship_id, :category_relationship_type

  belongs_to :category_relationshipable, polymorphic: true
  belongs_to :business
  belongs_to :post
  belongs_to :category

Category has these relationships:

has_many :category_relationships
  has_many :businesses, through: :category_relationships
  has_many :posts, through: :category_relationships

Post would have similar relationships as Business.

So now when I run Business.first.categories I get the error:

Business Load (6.1ms)  SELECT "businesses".* FROM "businesses" LIMIT 1
  Business Load (2.5ms)  SELECT "businesses".* FROM "businesses" INNER JOIN "category_relationships" ON "businesses"."id" = "category_relationships"."category_relationshipable_id" WHERE "category_relationships"."business_id" = 3 AND "category_relationships"."category_relationshipable_type" = 'Business'
ActiveRecord::StatementInvalid: PG::Error: ERROR:  column category_relationships.business_id does not exist
LINE 1: ...lationships"."category_relationshipable_id" WHERE "category_...
                                                             ^
: SELECT "businesses".* FROM "businesses" INNER JOIN "category_relationships" ON "businesses"."id" = "category_relationships"."category_relationshipable_id" WHERE "category_relationships"."business_id" = 3 AND "category_relationships"."category_relationshipable_type" = 'Business'

How do I structure the relationships so this works?

like image 757
bcackerman Avatar asked Dec 11 '22 14:12

bcackerman


1 Answers

Similar questions here: Rails polymorphic has_many :through And here: ActiveRecord, has_many :through, and Polymorphic Associations

I think it should be something like this:

class Category
  has_many :categorizations
  has_many :businesses, through: :categorizations, source: :categorizable, source_type: 'Business'
  has_many :posts, through: :categorizations, source: :categorizable, source_type: 'Post'
end

class Categorization
  belongs_to :category
  belongs_to :categorizable, polymorphic: true
end

class Business #Post looks the same
  has_many :categorizations, as: :categorizeable
  has_many :categories, through: :categorizations
end
like image 96
Shannon Avatar answered Dec 29 '22 12:12

Shannon