我有模特展览,他有测验。在测验中,我们有问题和答案属于它。我使用了嵌套属性。
我犯了错误,因为现在在rake db:seed rails之后,我只在问题中添加了最后一行。这是我种子展示的一个例子
e1 = Exhibit.create(
title: 'TITLE',
author: 'PICASOO',
date_of_origin: '300',
description: 'LOREM IPSUM',
ex_id: '1',
type: nil,
questions_attributes:[
content: "QUESTION 1?",
answers_attributes:[
content: "ANSWER 1",
correct: true,
content: "ANSWER 2",
correct: false, # if it's correct answer i change this var.
content: "ANSWER 3",
correct: false]
])
展示模型:
has_many :questions, :dependent=> :destroy
accepts_nested_attributes_for :questions,
:reject_if => lambda { |a| a[:content].blank? },
:allow_destroy => true
问题模型:
belongs_to :exhibit
has_many :answers, :dependent=> :destroy
accepts_nested_attributes_for :answers,
:reject_if => lambda { |a| a[:content].blank? },
:allow_destroy => true
答案模型:
class Answer < ActiveRecord::Base
belongs_to :question
end
答案 0 :(得分:2)
e1 = Exhibit.create(
title: 'TITLE',
author: 'PICASOO',
date_of_origin: '300',
description: 'LOREM IPSUM',
ex_id: '1',
type: nil,
{
:questions_attributes =>
{ 0 =>
{
content: "Q1",
:answers_attributes =>
{ 0 =>
{
content: "ANSWER 1",
correct: true
},
1 =>
{
content: "ANSWER 2",
correct: false
}
}
}
}
}
)
或:
e1 = Exhibit.create(
title: 'TITLE',
author: 'PICASOO',
date_of_origin: '300',
description: 'LOREM IPSUM',
ex_id: '1',
type: nil,
questions_attributes: [
{
content: 'Q1',
answers_attributes: [
{content: "A1", correct: false},
{content: "A2", correct: true}
]
}
]
)