简体   繁体   中英

Rails local_assign vs. local variables

Learning from the Rails guide , I don't understand how local_assign works below:

To pass a local variable to a partial in only specific cases use the local_assigns.

  • index.html.erb

     <%= render user.articles %> 
  • show.html.erb

     <%= render article, full: true %> 
  • _articles.html.erb

     <h2><%= article.title %></h2> <% if local_assigns[:full] %> <%= simple_format article.body %> <% else %> <%= truncate article.body %> <% end %> 

This way it is possible to use the partial without the need to declare all local variables.

How is the partial even being rendered by the show action when it has the name _articles , which will only show for the index action? I also don't see why you use add the option of full: true when you could have just used locals: {full:true} . What's the difference?

Regarding the use of local_assigns :

The point of this section of the guide is to show how to access optional locals in your partials. If a local variable name full may or may not be defined inside your partial, simply accessing full will cause an error when the local is not defined.

You have two options with optional locals:

First, using local_assigns[:variable_name] , which will be nil when the named local wasn't provided, or the value of the variable.

Second, you can use defined?(variable_name) which will be nil when the variable is not defined, or truthy (the string "local_variable" ) when the local is defined.

Using defined? is simply a guard against accessing an undefined variable, you will still have to actually access the variable to get its value:

  • if local_assigns[:full]
  • if defined?(full) && full

As for your specific questions:

How is the partial even being rendered by the show action when it has the name _articles, which will only show for the index action?

This is a typo . The correct partial name is _article.html.erb . Regardless of the action, index or show , the correct partial name is the singular of the model. In the case of rendering a collection of models (as in index.html.erb), the partial should still be singularly named.

I also don't see why you use add the option of full: true when you could have just used locals: {full:true} . What's the difference?

The point is that the full: true syntax is shorter. You have two identical options:

  • render partial: @article, locals: { full: true } or
  • render @article, full: true .

The second is significantly shorter and less redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM