2013-02-28 215 views
2

检索数据创建这样从嵌套哈希对象

@question = Question.new 
    3.times {@question.answers.build} 

形式如果不验证,我再次显示与填充数据的形式。不难填充不过,我遇到麻烦了答案模型会话哈希(其中有一个内容和链接字段)获得嵌套值问题的数据

@question = @user.questions.new(session[:question]) 

。这不起作用。

3.times {@question.answers.build(:content => session[:question][:answers_attributes][:content], :correctanswer => session[:question][:answers_attributes][:correctanswer]) } 

我认为这是因为哈希对象中的0,1和2次迭代。例如,这是从哈希对象片段(如下所示全)

"answers_attributes"=>{"0"=>{"content"=>"", 

但我不知道我怎么会表示,建设的问题时,回答

3.times {@question.answers.build(:content => session[:question][:answers_attributes][:content].... 

当我m试图构建我不试图从哈希对象中提取数据时表示迭代。你能解释一下我将如何修改这条线来传递参数到question.answers.build

这是散列对象。

> Parameters: {"utf8"=>"✓", "question"=>{"content"=>"Lick me", 
> "link"=>"bab", "answers_attributes"=>{"0"=>{"content"=>"", 
> "correctanswer"=>"0", "_destroy"=>"false"}, "1"=>{"content"=>"", 
> "correctanswer"=>"1", "_destroy"=>"false"}, "2"=>{"content"=>"", 
> "correctanswer"=>"0", "_destroy"=>"false"}}}, "commit"=>"Create 
> Question"} 
+0

我想存储相同格式的数据,请您发送模型和表格的代码。 – 2013-02-28 08:07:35

+0

这是所有在这个railscast http://railscasts.com/episodes/196-nested-model-form-revised – Leahcim 2013-02-28 08:17:00

+0

谢谢你的链接。 – 2013-02-28 08:20:32

回答

1

由于在参数三套键/值,它是通过参数更好地循环,并通过建立在每次迭代的questions.answers,像这样。通过这种方式,您可以通过传入密钥来表示嵌套哈希中的迭代。

@question = @user.questions.new(session[:question]) 
session[:question][:answers_attributes].each do |k,v| 
     @question.answers.build(:content => session[:question][:answers_attributes][k][:content], :correctanswer => session[:question][:answers_attributes][k][:correctanswer]) 

     end