0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, short sweet and I'm not repeating code. I should have thought of passing a variable in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.