How to structure multiple hierarchy levels in Ruby on Rails?

The rails app contains many different content pages. Pages are organized into small groups known as sections:

class Page < ActiveRecord::Base
   attr_accessible: section_id #etc..
   belongs_to :section
end

class Section < ActiveRecord::Base
  attr_accessible :title #, etc... 
  has_many :pages
end

Sections should also be organized, but what is the best way to do this - reuse the sections themselves or create a new Unit model?

Option 1 - Reuse Partition
Allow the partition to have child and parent sections. Thus, you do not need to create another model with similar fields, such as Section. Some sections will have several pages, while other sections will have several child sections:

class Section < ActiveRecord::Base
  attr_accessible :parent_id  :title # etc... 
  has_many :pages

  belongs_to :parent, class_name: "Section"
  has_many :children, class_name: "Section", foreign_key: "parent_id"
end

2 -
Unit . , .

class Section < ActiveRecord::Base
  attr_accessible :title, :unit_id # etc... 
  has_many :pages
  belongs_to :units
end

class Unit < ActiveRecord::Base
  attr_accessible :title # etc... 
  has_many :sections
end

1 , , . , 2 , , , , . ?


, 2 , , . , ? , , :

2 - . , - .

1 - . , .

+4
4

, . , . , 2+ , .

+2

( 1), , , . 2.

, , , :

1 - , . , ActiveRecord :

sections_with_parent = Section.joins(:parent)
sections_with_children = Section.joins(:children).uniq
parent_key_with_children_values = Section.joins(:children).uniq.inject({}) do |result, section|
  result.merge({section => section.children})
end
sections_with_no_parent = Section.where(parent_id: nil)

2 - :

sections_with_parent = Section.joins(:unit)
units_with_children = Unit.joins(:sections).uniq
parent_key_with_children_values = Unit.joins(:sections).uniq.inject({}) do |result, unit|
  result.merge({unit => unit.sections })
end
sections_with_no_parent = Section.where(unit_id: nil)

, , .

+3

, awesome_nested_set. , . Unit , , , , , . title... - . Unit 1 .

0

.

Mongodb (mongoid: http://mongoid.org/en/mongoid/index.html) .

class Page
  include Mongoid::Document

  embeds_many :sections, :class_name => 'Sections', :inverse_of => :page
end

class Section
  include Mongoid::Document
  field :title, :type => String, :default => ''

  embedded_in :page, :class_name => 'Page', :inverse_of => :sections
end
0

All Articles