如何创建具有多个字段的模型以获得答案?

时间:2015-03-26 18:21:27

标签: ruby-on-rails ruby model

我使用Questionquestion:string创建了一个模型answer:string

我想用多个答案创建问题(1-30),但在数据库中只有两个表(一个用于提问,一个用于回答)。

例如,我有一个问题字段和许多可以动态添加的答案字段。之后,我想显示问题以及属于它的所有答案。我该怎么做?

2 个答案:

答案 0 :(得分:2)

您希望将这些问题分开。 我的意思是: 制作单独的Answer模型和迁移,以便您可以创建“答案”。数据库中的表。这样你可以把它放在你的问题模型中:

has_many :answers

并在你的答案模型中:

belongs_to :question

我说这是达到你想要的正确方法。

答案 1 :(得分:0)

QuestionAnswer模型定义为

class Question < ActiveRecord::Base
    has_many :answers 
end

class Answer < ActiveRecord::Base
    belongs_to :question
end

RUn迁移

rails g migration addQuestionIdToAnswers question_id:integer

现在您可以说question.answers,这将为您提供属于该问题的所有answers。因为你在每个'答案&#39;

上都有question_id字段

您可以拨打电话

answer.question # return the question the answer `belongs_to`

question.answers # return all the answers the question `has_many`