[英]Ruby on Rails: How to get nested_form_for new child ID
我有QuestionSet,Question和Choice表
class QuestionSet < ActiveRecord::Base
attr_accessible :name
has_many :questions
end
class Question < ActiveRecord::Base
attr_accessible :name, :correct_answer
belongs_to :question_set
has_many :choices
end
class Choice < ActiveRecord::Base
attr_accessible :question_id, :value
belongs_to :question
end
我想將Choice的ID分配為Question的correct_answer。 但是,由於新的nested_form_for子對象還沒有真實ID,因此我只能為已經保存的選擇分配正確的答案,而不能對剛剛通過link_to_add創建的選擇起作用。 下面是簡化的“查看”代碼:
<!-- BTW 'f' below is QuestionSet -->
<%= f.fields_for :questions do |f_f| %>
<!-- Question Name -->
<%= f_f.text_field :name %>
<%= f_f.fields_for :choices do |f_f_f| %>
<!-- Designate as Correct Answer -->
<%= f_f.radio_button :correct_answer, f_f_f.object.id %><!-- THIS IS THE PROBLEM-->
<!-- Choice Name -->
<%= f_f_f.text_field :value %>
<%= f_f_f.link_to_remove "Remove Choice" %>
<% end %>
<%= f_f.link_to_add "Add Choice", :choices %>
<%= f_f.link_to_remove "Remove Question" %>
<% end %>
<%= f.link_to_add "Add Question", :questions %>
同樣,該代碼僅在選擇項已被保存且因此已經具有ID的情況下才有效,並且將選擇子項的ID分配為問題的“ correct_answer”。 但是,它對於那些由link_to_add創建的新創建的選擇子項無效。
任何幫助將不勝感激。 謝謝! :)
為什么不將:correct_answer字段移至Choices並將其設為布爾值? 這將簡化很多事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.