我有三个模型Report , Question , Answer
回答
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 %>
---Partial Answer_Fields--- <%= f.text_field :name, :placeholder => "在这里添加你的答案" %>
但是,当我尝试编辑/创建新报告时,它会获取该特定问题的所有现有答案。而我想实现类似的东西:
---部分问题_字段---
<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