从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}
。有什么不同?
'render:locals:{full:true}'和'render full:true'之间没有实际区别,它们都分配一个名为'full'的局部变量,后者只是一个较新的简写。 – max
关于你的第一个问题,名字'_articles'是一个错字。部分名称应该是'_article'。我已经打开了一个[pull request to fix the guide](https://github.com/rails/rails/pull/27896) – meagar