我有三个模型报告,问题,答案
belong_to :question
belong_to :reports
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :allow_destroy => true
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :allow_destroy => true
在创建新报告时,会随机选择一些问题,以便以这种方式添加到报告和展示表单中:
报告表
<%= form_for @report do |f| %>
<div class="field">
<%= f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder %>
<% end %>
</div>
<div class="actions">
<%= f.submit "Submit Report"%>
</div>
<% end %>
---部分问题_字段---
<h4 class="question_name">
<%= f.object.name %>
</h4>
<%= f.fields_for :answers do |answer,index| %>
<%= render 'answer_fields', :f => answer %>
<% end %>
---部分答案_字段--- &lt;%= f.text_field:name,:placeholder =&gt; “在这里添加你的答案”%&gt;
但是当我尝试编辑/创建新报告时,它会获取该特定问题的所有现有答案。我希望实现类似的东西:
---部分问题_字段---
<h4 class="ques_title">
<%= f.object.name %>
</h4>
<% f.object.answers_for_report(@report).each do |answer| %>
<%= render 'answer_fields', :f => answer %>
<% end %>
---部分问题_字段---
<b>What should be code here so that it again acts same as nested attributes and gets updated succesfully !!!</b>
belong_to :reports
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :allow_destroy => true
def answers_for_report(@report)
self.answers.where("report_id = ? ",report.id)
end
答案 0 :(得分:1)
以下是我的问题的答案:
报告表格就像
<%= form_for @report do |f| %>
<div class="field">
<%= f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder %>
<% end %>
</div>
<div class="actions">
<%= f.submit "Submit Report"%>
</div>
<% end %>
然后问题'question_fields'就像
<%= question.fields_for :answers, question.object. answers_for_report(@report) do |answer| %>
<%= render 'answer_fields', :f => answer %>
<% end %>
这仅传递答案记录的集合/集合,并仅为这些选定答案呈现字段。