【问题标题】:ActiveRecord model with variable number and order of fields as relations以可变数量和字段顺序作为关系的 ActiveRecord 模型
【发布时间】:2016-07-21 19:36:51
【问题描述】:

我正在尝试使用 Google 表单创建具有类似功能的应用程序,用户可以在其中确定不同问题类型的模板,然后为每个模板收集多个响应。具体来说,我需要创建具有用户确定数量(和顺序)的免费回复(段落文本字段)和图片上传问题的表单。

如何在 ActiveRecord 中设置此方案?我正在考虑使用FormResponse 模型来存储每个响应,其中has_many 类型为QuestionResponse 的模型用于对每个问题的响应,TextResponseUploadResponse 模型作为@987654326 的单表继承类@。有没有更优雅的方法来使用 ActiveRecord 存储这种结构?我应该如何在这样的模式中存储模板、问题的结构?我最好使用 Mongo 的灵活文档模型并将问题响应文档嵌入表单响应文档内的列表中吗?

【问题讨论】:

  • 如果我这样做,我可能会使用您提出的模型。我将添加一个问题类(可能还有子类),其中包含有关问题、验证和 answer_data_type 的详细信息。然后,您可以多态地将您的 QuestionResponse 与该类相关联。我认为 mongo 肯定也会起作用。就我个人而言,我更喜欢关系型数据库。

标签: ruby-on-rails activerecord


【解决方案1】:

一个常见的概念是分别考虑结果和调查问卷,并将每个受访者的所有汇总结果存储在单个记录中。如果您使用 Postgres,您可能会使用这种 JSON 数据类型。或者,单个 Mongo 文档也可以工作。

【讨论】:

    【解决方案2】:

    您不需要使用单表继承来完成此操作。

    # Surveys have questions
    class Survey < ActiveRecord::Base
        has_many :survey_questions
    end
    class SurveyQuestion
        belongs_to :survey
        belongs_to :question, polymorphic: true
        acts_as_list # This is where you order your questions
    end
    
    # Questions are independent, and can be used
    # in multiple Surveys
    class UploadQuestion < ActiveRecord::Base; end
    class TextQuestion < ActiveRecord::Base; end
    
    # User responses are associated with the specific
    # question as it appears in a Survey. Response
    # table rows don't need extraneous columns.
    class User < ActiveRecord::Base; end
    class TextResponse < ActiveRecord::Base
        belongs_to :user
        belongs_to :survey_question
    end
    class UploadResponse < ActiveRecord::Base
        belongs_to :user
        belongs_to :survey_question
    end
    

    【讨论】:

    • 这种方法相对于 STI 的好处是我们可以节省数据库表列的复杂性并且我们可以轻松地扩展更多的问题类型,但代价是 SurveyQuestion 模型中的模型逻辑更复杂?
    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2013-08-19
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多