← Back to Upcase

Is there a common way to represent these similar associations?

(Paul Morganthall) #1

I have several categorized lists of things, all headed for select with optgroup. For example:


  • warm
    • red
    • orange
  • cool
    • violet


  • serif
    • Times New Roman
  • san-serif
    • Helvetica

I have nice models for Font and Color that I’m happy with. I’m less satisfied with my ColorCategory and FontCategory models. I suppose someday they’ll grow specific behavior, but right now they’re duplicates except for the models they categorize. Am I worrying about nothing or is there some Rails convention for handling a pattern like this?

(David Paquet) #2

Maybe something like this solution?

class Post < ActiveRecord::Base
  has_one :categorization, :as => :categorizable
  has_one :category, :through => :categorization

class Category < ActiveRecord::Base
  has_many :categorizations, :dependent => :destroy

class Categorization < ActiveRecord::Base
  belongs_to :category
  belongs_to :categorizable, :polymorphic => true

Source :

(Sean Griffin) #3

Generally speaking, if there’s no specific behavior or additional data modeling coming from these categories, there’s not really any reason that they need to be a separate model. Why not just have a string type column on Color and Font called Category? If you need to break it out into a separate table at a later date, it’s very easy to do.

(Paul Morganthall) #4

I’d been trying to figure out how polymorphic associations might be used here – thanks for that reference.

I inherited the category models from a different app and hadn’t questioned them until now. I think a Category string on each item will work here. I just need to convert ColorCategory.all.each to something like Color.all.group_by {|color| color.category}

Thanks for the ideas.