Thursday, February 28, 2008

Rails Polymorphic better_nested_set

better_nested_set is a great Rails plugin for representing hierarchical data. Recently I worked on a problem where a message board feature needed to be created that could not only have multiple message trees but also needed to have multiple message trees referring to different model types. Instead of splitting these up into multiple tables, one for each model type, the acts_as_nested_set :scope parameter along with polymorphic associations can be used to store all the messages in a single table. Here is some sample code:



By combining better_nested_set and polymorphic associations the amount of work needed to introduce a new discussable type is reduced by reducing the number of models and number of tables.

No comments:

Post a Comment