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

1

0

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
Skyline answered 4/12, 2012 at 9:6 Comment(1)
Got a clue from #10506353 how to add a prticular collection into answers and work with nested attributesSkyline
S
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.

Skyline answered 16/1, 2013 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.