从视图ROR呈现部分视图 [英] Render form partial from view ROR
问题描述
这是posts_index,render post.comments可以正常工作,但新的窗体
<%@ posts.each do | post | %GT;
<%= link_to post.title,post%>
<%= simple_format post.text%>
<%=呈现post.comments.order('created_at DESC')。all%>
<%= render:partial => '/ comments / form',当地人:{post:post}%>
我得到这个错误:未定义的方法'comments'for nil:NilClass
评论表:
<%= form_for([@ post,@ post.comments .build])do | f | %GT;
<%= f.label:评论%>< br />
<%= f.text_area:body,:class => comment_text_box%>
<%= f.submit%>
<%end%>
我明白我需要将post.comments传递给表单,但无法弄清楚。
$ b
Post_show可以与<%= rendercomments / form%>
$ b
帖子和评论是 has_many
关系,帖子 has_many
评论。
感谢您的关注。
您需要像下面这样将变量传递到您的部分:
<%@ posts.each do | post | %GT;
<%= link_to post.title,post%>
<%= simple_format post.text%>
<%=呈现post.comments.order('created_at DESC')。all%>
<%=呈现部分:'/ comments / form',当地人:{post:post}%>
<%end%>
并将您的表单部分更改为:
<%= form_for([post,post.comments.build])do | f | %GT;
//表单域
<%end%>
Im trying to render a form from another controller in my view.
This is posts_index, and the render post.comments works fine, but the form for a new comment doesnt.
<% @posts.each do |post| %>
<%= link_to post.title, post %>
<%= simple_format post.text %>
<%= render post.comments.order('created_at DESC').all %>
<%= render :partial => '/comments/form', locals: {post: post} %>
I get this error: undefined method `comments' for nil:NilClass
The comments form:
<%= form_for([@post, @post.comments.build]) do |f| %>
<%= f.label :Comment %><br />
<%= f.text_area :body, :class => "comment_text_box" %>
<%= f.submit %>
<% end %>
I understand I need to pass the post.comments to the form, but can't figure out how.
Post_show works with <%= render "comments/form" %>
Post and comments are a has_many
relationship, posts has_many
comments.
Thanks for looking.
You need to pass variables into your partial like this:
<% @posts.each do |post| %>
<%= link_to post.title, post %>
<%= simple_format post.text %>
<%= render post.comments.order('created_at DESC').all %>
<%= render partial: '/comments/form', locals: {post: post} %>
<% end %>
and change your form partial to this:
<%= form_for([post, post.comments.build]) do |f| %>
// form fields
<% end %>
这篇关于从视图ROR呈现部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!