Render form partial from view ROR

血红的双手。 提交于 2019-12-11 06:59:28

问题


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.


回答1:


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



回答2:


When you ask for the partial, you need to send it the post it's related to. It would look 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', post: post%>


来源:https://stackoverflow.com/questions/26219900/render-form-partial-from-view-ror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!