Organize lecture with chapter and lesson models

89 Views Asked by At

I am trying to organize my models so that I get to see in lecture.rb > chapter.rb > lesson.rb. As you can imagine chapter.rb have to be organized by order in the view as well as the nested lesson within chapters.

It is a bit confusing.. My idea so far was to create those models.

class Lecture
has_many :lessons, through: :chapters
has_many :chapters
end

class Chapter
# lecture_id / name / should I use an integer to order it ? 
has_many :lessons 
belongs_to :lecture
end

class Lesson 
# I added a :step which is an integer in order to order them?
belongs_to :lecture
belongs_to :chapter
end

Is there a better way of doing that ? The main purpose is to well organize the lectures.

1

There are 1 best solutions below

0
On BEST ANSWER

You might want a lambda scope block. Try this:

class Lecture < ActiveRecord::Base
  has_many :chapters, -> { order(number: :asc) }
  has_many :lessons, through: :chapters
end

class Chapter < ActiveRecord::Base
  belongs_to :lecture
  has_many :lessons
end

class Lesson < ActiveRecord::Base
  belongs_to :chapter
  has_one :lecture, through: :chapter
end

got it from Deprecated warning for Rails 4 has_many with order

This would work with a integer column 'number' in the chapters table. You could do the same with Lessons if they have an order.