2017-02-03 27 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

第二個顯着更短,更少冗餘。