2016-06-09 60 views
1

我有模型展覽,他有測驗。在測驗中,我們有問題和答案屬於它。我使用嵌套屬性。如何在種子文件中添加嵌套屬性Rails

我在哪裏犯錯,因爲賴特現在後耙db:種子軌添加我只問最後一行。這裏是我的例子種子中的一個展品

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

在每個答案的「正確」屬性後刪除每個','。仔細檢查我的答案以找出差異。 – Emu

+0

更新了我的答案。請檢查添加的代碼是否有效。 – Emu

回答

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} 
    ] 
    } 
] 
)