Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby on Rails, render 'shared/score', :locals => { :score => @foo.score } will not pass in the local?

Maybe I missed something in http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials

It seems that to render a partial, we can use

render 'shared/score'

but the next section talks about locals

render :partial => 'bar', :locals => { :score => @foo.score }

But what about the first form?

render 'shared/score', :locals => { :score => @foo.score }

The line above will not pass in the locals, why?

It seems like it has to be

render :partial => 'shared/score', :locals => { :score => @foo.score }

but why is that? (I am using Rails 3.0.6)

like image 676
nonopolarity Avatar asked Apr 12 '11 16:04

nonopolarity


1 Answers

You actually want:

render 'shared/score', { :score => @foo.score }

Explanation

You can look at this for their source code on render.

http://api.rubyonrails.org/classes/ActionView/Rendering.html#method-i-render

If you see that if the first parameter is NOT a hash, it will default to that being the name of the partial, and pass the second paramater as locals.

The catch is that it wants the locals of in the 2nd paramater. :locals => {:score => @foo.score} may seem right at first, but you actually want: {:score=> @foo.score}.

The reason for this is that it sets the :locals option for the _render_partial method to the second paramater. So if you were to do it your way, it would actually look like:

:locals => {:locals => {:score=>@foo.score}}

Which doesn't make much sense.

like image 73
Mike Lewis Avatar answered Oct 01 '22 21:10

Mike Lewis