繁体   English   中英

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

[英]Rails partial locals not working

我有

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 (请忽略索引上的数据切换,它还无法正常工作)

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM