RobertJoseph
RobertJoseph

Reputation: 8158

Passing parameters to Rails partial

In my Rails 4.2.1 app I have Posts and Comments (which are nested within Posts):

   # config/routes.rb

   resources :posts do
      resources :comments
   end

I have the following Comments partial:

   # app/views/comments/_comment.html.erb

   <%= comment.body %>

I'm trying to render that partial from within a Posts view:

   # app/views/posts/show.html.erb

   <% @comments.each do |comment| %>
     <%= render 'comments/comment', :locals => { :comment => comment } %>
   <% end %>

The problem is that I'm getting an undefined local variable or method "comment" error when trying to render the partial.

I'm pretty new to Rails but it looks to me like I am passing the comment variable to the partial correctly. Am I missing something obvious?

Thanks

Update

I was looking in the wrong spot in the documentation. See http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

enter image description here

Upvotes: 1

Views: 4695

Answers (3)

Rubyrider
Rubyrider

Reputation: 3587

Try the short hand method for rendering partials. This is more preferred as you do not have to specify the other options.

 <%= render 'comments/comment', { :comment => comment } %>

Read this URL to learn more; http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html

Upvotes: 0

webster
webster

Reputation: 4012

Passing variables via locals hash is not supported in the shorthand syntax of rendering a partial. In that case you can use this one:

<%= render 'comments/comment', :comment => comment  %>

Upvotes: 1

j-dexx
j-dexx

Reputation: 10406

Either add in partial

<%= render partial: 'comments/comment', :locals => { :comment => comment } %>

Or render the collection: This does it via rails using the model name

<%= render @comments %>

Or explicitly

<%= render partial: 'comments/comment', collection: @comments %>

Upvotes: 6

Related Questions