Mohamed Mokhtari Mohamed Mokhtari - 1 year ago 80
Ruby Question

Rails multiple post types : nested forms and complex association

I have a problem in figuring out the best approach for creating a lecture and quiz for an education platform.

First of all I have two models :


class Course < ApplicationRecord
has_many :sections
accepts_nested_attributes_for :sections, reject_if: :all_blank, allow_destroy: true


class Section < ApplicationRecord
belongs_to :course

and in the view I am using cocoon gem for nested forms and creating course and sections from the same new page.

My goal is to have a Lesson model which has two types (lecture which is a video with notes and comments, and a quiz with questions and answers), the problem is I couldn't figure out the right approach for such a problem.

So this is what came in my head so far :

Approach 1 :

using STI , so I have a lesson model which belongs to a section, and have two models that inherit from the lesson model lecture and quiz like so :


class Lesson < ApplicationRecord
belongs_to :section


class Lecture < Lesson


class Quiz < Lesson

and what confuses me here is the quiz model it will has so many other associations like questions, answers and right answers so I wonder if i am in the right path or no ?

Approach 2 :

using Dynamic Forms from railscasts which I find it the more confusing approach for such issue.

keep in my mind I need them both of lecture and quiz model to belong to a lesson model so I can list the data as a list and I can keep track for progress.

Update 1 :

or should I create independent models for both quiz and lecture and make them belong to a lesson model, where the lesson model has_one quiz or lecture.

Answer Source

First, decide the best data model and ignore the presentation. After that, focus on how you want to present the data.

I would recommend using a "has a" relationship rather than STI - in other words the approach you recommend in your "update 1". The reason is that the lecture and the quiz seem very different so they don't seem like good candidates for STI. You could go with a polymorphic "lesson_content" relation between the Lesson and Quiz/Lecture objects, but I would start with a plain has_one/ has_many.

Once you have that implemented you can use Cocoon or roll your own dynamic forms. I found the (excellent) Railscast outdated and wrote up a blog post that might be of use here: Dynamic forms with Rails 4

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download