如何在选定记录的轨道中为nested_attributes创建文本字段? [英] How to make text fields for nested_attributes in rails for selected records?

查看:86
本文介绍了如何在选定记录的轨道中为nested_attributes创建文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个模型报告问题答案

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

在创建新报告时,会随机选择一些问题以这种方式将其添加到报告并显示表单:

While creating a new report some questions are randomly picked to be added to the report and show form in this way :

报告表格

    <%= 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 %>

---部分答案字段--- <%= f.text_field:name,:placeholder =>在此处添加答案"%>

---Partial Answer_Fields--- <%= f.text_field :name, :placeholder => "Add your answer here" %>

但是,当我尝试编辑/创建新报告时,它将获取该特定问题的所有现有答案.而我想实现类似以下内容:

But when I try to edit/create a new report it fetches all the existing answers for that particular question. Whereas I want to implement something like :

---部分问题字段---

<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

推荐答案

这是我的问题的答案:

报告表格就像

<%= 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"就像

Then Question 'question_fields' is like

<%= question.fields_for :answers, question.object. answers_for_report(@report) do |answer| %>  
    <%= render 'answer_fields', :f => answer %>  
<% end %>

这仅传递答案的记录/记录集,并且仅呈现那些选定答案的字段.

This passes only a collections / set of records of answers and renders fields for those selected answers only.

这篇关于如何在选定记录的轨道中为nested_attributes创建文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆