如何在ActiveRecord中为问答数据结构建模?

时间:2019-10-20 19:28:54

标签: ruby-on-rails activerecord

这感觉应该很简单,但是对于我一生来说,我一直无法正确解决问题。

在我的应用程序中,我想拥有QuestionsAnswers

一个Question只能有1个Answer,但是一个Answer可以用于许多Question

例如。

问题表数据

  1. “二加二等于?”
  2. “正方形的边数是多少?”

答案表数据

  1. 四个

两个Question仅具有1个Answer,但是Answer记录可同时用于两个Questions

我认为这可能会起作用::

rails g resource question verbiage:string answer:references

但是然后我必须在belongs_to :answer模型上放置一个Question,但这似乎不正确。

感觉应该可以进行:::

Question.first.answer # returns the single answer

Answer.first.questions # returns all of the Questions where this record is the Answer

有人可以教我关于在ActiveRecord中进行建模的正确方法吗?

3 个答案:

答案 0 :(得分:2)

如果您不想使用

的demir答案
  • 问题归属于答案
  • 回答has_many问题

您必须

  • 创建一个QuestionAnswer联接表
  • QuestionAnswer属于问题
  • QuestionAnswer属于自己的答案
  • 问题has_one个问题_answers
  • answer has_many question_answers

然后

  • 问题has_one:answer到:question_answer来源:answer
  • answer has_many:question到:question_answer来源:question

例如https://guides.rubyonrails.org/association_basics.html#choosing-between-belongs-to-and-has-one

  

例如,说一个供应商拥有一个帐户比说一个账户拥有一个供应商更有意义。这表明正确的关系是这样的

答案 1 :(得分:2)

您需要has_many关联。 我要为此使用脚手架。

  1. 创建答案:

    rails g scaffold Answer value:string
    
  2. 创建问题:

    rails g scaffold Question verbiage:string answer:references
    
  3. 运行rails db:migrate

  4. 创建关联。

    class Answer < ApplicationRecord
      has_many :questions
    end
    
    class Question < ApplicationRecord
      belongs_to :answer
    end
    

答案 2 :(得分:1)

这实际上取决于要求。在大多数情况下,您实际上需要一个联接表:

class Question
  has_many :options
  has_many :answers, through: :options
end

class Option
  belongs_to :question
  belongs_to :answer
end

class Answer
  has_many :options
  has_many :questions, through: :options
end
answers = [Answer.create(verbiage: 'Dailey'), Answer.create(verbiage: 'Once a week'), Answer.create(verbiage: 'Never')]
question = Question.create(verbiage: 'How often do you drink milk?', answers: answers)
question_2 = Question.create(verbiage: 'How often do you excercise?', answers: answers)

如果问题的答案正确,则可以使用单独的关联,该关联是指向答案表的直接链接:

class Question
  has_many :options
  has_many :answers, through: :options
  belongs_to :correct_answer, class_name: 'Answer'
end

或者如果options表可以是多个正确答案,则可以将布尔列添加到表中。

class Question
  has_many :options
  has_many :answers, through: :options
  has_many :correct_answers, through: :options, 
                             class_name: 'Answer',
                             -> { where(options: { correct: true }) }
end