views:

277

answers:

1

Say I'm writing a blog app with models for posts, pages and photos. I've got a category model, that may be linked to any of these models. So, a category may contain various kinds of items. Every item only has ONE category.

I could implement this using a generic tagging pattern with a join table, but I want to make sure every subject can have only category.

What would be the best way to implement this in Rails?

+4  A: 

Okay, I think I've got it:

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

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

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

Now various models can have a category, but each instance can have only one category… I guess.

avdgaag
Excellent. I've been banging my head on the desk trying to work this out. Thanks!
Kapslok