用章节和课程模型组织讲座
Organize lecture with chapter and lesson models
我正在尝试组织我的模型,以便在 lecture.rb > chapter.rb > lesson.rb 中看到。正如您想象的那样,chapter.rb 必须按视图中的顺序以及章节中的嵌套课程进行组织。
有点混乱..到目前为止,我的想法是创建这些模型。
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
有更好的方法吗?主要目的是组织好讲座。
您可能需要一个 lambda 作用域块。试试这个:
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
来自 Deprecated warning for Rails 4 has_many with order
这适用于章节 table 中的整数列 'number'。如果他们有订单,您可以对 Lessons 做同样的事情。
我正在尝试组织我的模型,以便在 lecture.rb > chapter.rb > lesson.rb 中看到。正如您想象的那样,chapter.rb 必须按视图中的顺序以及章节中的嵌套课程进行组织。
有点混乱..到目前为止,我的想法是创建这些模型。
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
有更好的方法吗?主要目的是组织好讲座。
您可能需要一个 lambda 作用域块。试试这个:
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
来自 Deprecated warning for Rails 4 has_many with order
这适用于章节 table 中的整数列 'number'。如果他们有订单,您可以对 Lessons 做同样的事情。