How to make text fields for nested_attributes in rails for selected records?

我与影子孤独终老i 提交于 2019-12-12 00:34:44

问题


I have a three models Report,Question,Answer

Answer

belong_to :question

Question

belong_to :reports
has_many :answers, :dependent => :destroy  
accepts_nested_attributes_for :answers, :allow_destroy => true

Reports

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 :

Report Form

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

---Partial Question_Fields---

<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 => "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 :

---Partial Question_Fields---

<h4 class="ques_title">
    <%= f.object.name %>
</h4>

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

---Partial Question_Fields---

  <b>What should be code here so that it again acts same as nested attributes and gets updated succesfully !!!</b>

Question Model

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

回答1:


Here is the answer to my question :

Report Form is like

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

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.



来源:https://stackoverflow.com/questions/13699285/how-to-make-text-fields-for-nested-attributes-in-rails-for-selected-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!