Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

ruby on rails - render partial :object vs :locals

<%= render :partial => 'partial/path', :locals => {:xyz => 'abc'} %>

vs

<%= render :partial => 'partial/path', :object => @some_object %>

I think the first one make a local variable named xyz available in the partial and the second one makes a local variable named object available in the partial. So what is the difference? (Besides locals allows more than one variable)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The second form

render :partial => 'account', :object => @some_account

will make sure the account variable in the partial will be set to @some_account. You can rename the variable using the :as option.

The biggest advantage of the :locals is that

  • you have very clear control over the objects and names
  • you can assign more than 1 variable

So you could do something like

render partial => 'some_view', :locals => { :user => account.user, :details => some_details_we_retrieved }

making a clear seperation possible when needed.

The disadvantage of the :locals approach is that it is more verbose, and sometimes a simple

render :partial => 'account'

is identical to

render :partial => 'account', :locals => {:account => @account }

So use the one which suits you the best (or where it suits the best).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...