Topic: Floating Key

Hi All,

I have a question regarding a design choice for an application I am building.

I have several classes that are related to a class call Comment:

Comment attributes as I see them are:

parent_id would be the id from the class that contains the comment and the parent_type would be the class name.

So at one point it could be class1 with a parent_id from class1 and also class2 with a parent_id from class2.  The disctinction would be held in the parent_type.

My question is how to configure this in Rails.
What do I use in belongs_to and has_many?

I am trying to avoid having to use a seperate column for class1_id and class2_id because the class could extend in the future.

Any comments?  Should I change the design?


Re: Floating Key

This is a good design. It is called Polymorphic Association in Rails. You just need to set up the association like this:

class Post < ActiveRecord::Base # or any model that can have comments
  has_many :comments, :as => :parent

class Comment < ActiveRecord::Base
  belongs_to :parent, :polymorphic => true

That's all there is to it, Rails will handle the rest with placing the class name in the parent_type column, etc.

Normally the name "parent_id" is used for a tree association. I don't think there will be any conflicts here, but you may want to rename it to "commentable_id" and "commentable_type".

Railscasts - Free Ruby on Rails Screencasts