NorCalKnockOut
NorCalKnockOut

Reputation: 878

Render form partial from view ROR

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.

Upvotes: 1

Views: 636

Answers (2)

Mandeep
Mandeep

Reputation: 9173

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

Upvotes: 1

Anthony
Anthony

Reputation: 15977

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

Upvotes: 0

Related Questions