Reputation: 596
I got
Class Question < ActiveRecord::Base
has_many :answers
end
and
class Answer < ActiveRecord::Base
belongs_to :question
end
My index action of question list all the questions and the basic CRUD actions.
<% @questions.each do |question| %>
And inside this loop I have another to show all answers to that question
<% question.answers.each do |answer| %>
After the action buttons I rendered the answer form partial
<%= render partial: 'answers/form' , question_id: question.id%>
But when them partial is rendered the question_id
to the answer is aways 1.
I also tried
<%= render partial: 'answers/form', :locals => {:question_id => question.id} %>
Still no success. This is the full index and form codes. https://gist.github.com/CassioGodinho/7412866 (Please ignore the data-toggle on the Index, its also not working yet)
Upvotes: 1
Views: 5808
Reputation:
Its not a good practice to pass new instance variable as local to a partial you can build the answer and then pass it as locals
<%= render partial: 'answers/form', :locals => {:answer => question.answers.build} %>
and in partial
<div class="answer_form">
<%= form_for(answer) do |f| %>
<% if answer.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(answer.errors.count, "error") %> prohibited this answer from being saved:</h2>
<ul>
<% answer.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div>
<%= f.label :question %>
<%= f.collection_select(:question_id, @questions, :id, :title) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</div>
Upvotes: 2
Reputation: 596
As Thomas Klemm showed it was easier to pass the @answer to the partial.
<%= render partial: 'answers/form', :locals => {:@answer => question.answers.build} %>
Upvotes: 0