Rails部分本地人无法正常工作

时间:2013-11-11 13:07:08

标签: ruby-on-rails

我得到了

Class Question < ActiveRecord::Base
    has_many :answers
end

class Answer < ActiveRecord::Base
    belongs_to :question
end

我的问题索引操作列出了所有问题和基本的CRUD操作。

<% @questions.each do |question| %>

在这个循环中,我有另一个显示该问题的所有答案

<% question.answers.each do |answer| %>

在动作按钮之后,我将答案形成为部分

<%= render partial: 'answers/form' , question_id: question.id%>

但是当它们部分呈现时,答案的question_id就会消失1。

我也试过

<%= render partial: 'answers/form', :locals => {:question_id => question.id} %>

仍然没有成功。 这是完整的索引和表单代码。 https://gist.github.com/CassioGodinho/7412866 (请忽略索引上的数据切换,它还无法正常工作)

2 个答案:

答案 0 :(得分:2)

将新的实例变量作为局部变量传递给局部变量并不是一个好习惯 你可以建立答案,然后将其作为当地人传递

<%= render partial: 'answers/form', :locals => {:answer => question.answers.build} %>

和部分

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

答案 1 :(得分:1)

正如Thomas Klemm所说,将@answer传递给部分更容易。

<%= render partial: 'answers/form', :locals => {:@answer => question.answers.build} %>