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:

class Message < ActiveRecord::Base
acts_as_nested_set :scope => 'discussable_id = #{discussable_id} AND discussable_type = \'#{discussable_type}\''
belongs_to :discussable, :polymorphic => true
# ...
end
class Foo < ActiveRecord::Base
has_many :messages, :as => :discussable
end
class Bar < ActiveRecord::Base
has_many :messages, :as => :discussable
end
view raw gistfile1.rb hosted with ❤ by GitHub


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.