0
votes

I have a comment controller that uses a form partial to add comments. Now this controller is nested under any parent resource that needs to have comments.

resource :post do
  resource :comments
end
resource :poll
  resource :comments
end

If I want to have a form partial that automatically configured for the proper resource how would I do it?

Right now I have to set up forms on the page of the nested resource like so:

<%= form_for [@post, @comment] do |f| %> <%= f.label :title %>
<%= f.text_field :title %> <%= f.label :body %>
<%= f.text_area :body %> <%= f.submit %> <% end %>

I would like to have a partial that looks something like the above code but that I can just call <%= render 'comments/form' %>

Any ideas on the best way to make this happen?

1

1 Answers

1
votes

You can solve this problem by passing a local variable to the comments partial using the locals hash:

In your nested resource, lets say, post's view:

<%= render 'comments/form', :locals => {:resource => @post} %>

Your comments form :

<%= form_for [resource, @comment] do |f| %>
  <%= f.label :title %> 
  <%= f.text_field :title %> <%= f.label :body %>  
  <%= f.text_area :body %> <%= f.submit %>
<% end %>

Also, I encourage you to go through this guide on partials where the details are explained.