is_type_of and is_a_category_for vs: belongs_to and has_many

Hello experts, I wonder if I'm the only one who is running into this conceptual stumbling block...

Suppose I have a database of documents, and I want to categorize the documents. I can model this as:

class document_category < ActiveRecord::Base   has_many :documents end

class document < ActiveRecord::Base   belongs_to :document_category end

but, semantically, I would rather write:

class document < ActiveRecord::Base   is_type_of :document_category end

class document_category < ActiveRecord::Base   is_a_category_for :documents end

(Or use some other sort of verbiage). The focus of my database is on the the documents, not the categories. The user entry fields are all going to be document-centric, (with, probably a drop-down box selecting the category for a document).

This is inverted from the classic Rails tutorials where a post might have many comments, or a supplier might have many widgets.

I am curious what folks do in this situation... Have you just learned (as I will) to live with the underlying meaning of "has_many" and "belongs_to"? Or do you define your own relationship mappings according to your problem domain. (If so, how would one do that?)

--wpd

Patrick Doyle wrote:

but, semantically, I would rather write:

class document < ActiveRecord::Base   is_type_of :document_category end

class document_category < ActiveRecord::Base   is_a_category_for :documents end

At the end of config/environment.rb, if you put:

class << ActiveRecord::Base   alias_method :is_type_of, :belongs_to   alias_method :is_a_category_for, :has_many end

then you can use these instead.

Thanks. That's a handy trick to know. I'll use that.

From a coding style perspective, is this what people generally do? Or does everybody accept and understand the semantic meanings of belongs_to and has_many?

--wpd

Patrick Doyle wrote:

From a coding style perspective, is this what people generally do? Or does everybody accept and understand the semantic meanings of belongs_to and has_many?

Personally, I always just use has_many/belongs_to as that is the relationship between the models.

If you use something non-standard, then someone else coming to your code would have to look for the definition in documentation or the source somewhere, no matter how clear the names, to be certain in themselves what is meant. That doesn't mean you shouldn't do it. Rails is opinionated, but not restrictive.