2017-02-03 96 views
1

Rails guide学习,我不明白下面local_assign是如何工作的:Rails的local_assign与局部变量

传递一个局部变量的部分仅在特定情况下使用 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 %> 
    

这样就可以使用局部变量而不需要声明 。

如果show action的名称为_articles,它只会显示索引操作,它是如何渲染的?我也不明白你为什么使用full: true时可以使用locals: {full:true}。有什么不同?

+0

'render:locals:{full:true}'和'render full:true'之间没有实际区别,它们都分配一个名为'full'的局部变量,后者只是一个较新的简写。 – max

+0

关于你的第一个问题,名字'_articles'是一个错字。部分名称应该是'_article'。我已经打开了一个[pull request to fix the guide](https://github.com/rails/rails/pull/27896) – meagar

回答

4

关于使用local_assigns

指导本节的重点是展示如何访问可选当地人在你的谐音。如果局部变量名称full可能是或可能不是被定义在您的局部变量中,那么只要访问full就会在未定义局部变量时导致错误。

你有两个选择与可选当地人:

首先,使用local_assigns[:variable_name],这将是nil命名的本地未提供时,或变量的值。

其次,你可以使用defined?(variable_name)这将是nil没有定义的变量时,或truthy(字符串"local_variable")当本地是定义

使用defined?仅仅是针对访问未定义的变量保护,你仍然有实际访问变量来获得它的值:

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

由于为您的具体问题:

如果show action的名称_articles只显示索引操作,它是如何呈现的?

This is a typo。正确的部分名称是_article.html.erb。无论动作如何,indexshow,正确的部分名称是模型的单数。在渲染模型集合的情况下(如index.html.erb),部分仍应该单独命名。

我也不明白你为什么使用时添加full: true选项,当你刚才可以使用locals: {full:true}。有什么不同?

问题是full: true语法更短。你有两个相同的选择:

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

第二个显着更短,更少冗余。