重构
现在我们已经有可以操作的articles和comments,来看一下模板app/views/articles/show.html.erb。它变得越来越冗长和笨拙。我们可以用局部文件来清理.
7.1 Rendering Partial Collections
首先,我们来建一个comment的局部文件, 把用来显示article所有的comment提取出来。创建这个文件 app/views/comments/_comment.html.erb,编辑上下面的代码:
<p> <strong>Commenter:</strong> <%= comment.commenter %> </p>
<p> <strong>Comment:</strong> <%= comment.body %> </p> |
接着你可以编辑文件 app/views/articles/show.html.erb:
<p> <strong>Title:</strong> <%= @article.title %> </p>
<p> <strong>Text:</strong> <%= @article.text %> </p>
<h2>Comments</h2> <%= render @article.comments %>
<h2>Add a comment:</h2> <%= form_for([@article, @article.comments.build]) do |f| %> <p> <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> <%= f.submit %> </p> <% end %>
<%= link_to 'Edit Article', edit_article_path(@article) %> | <%= link_to 'Back to Articles', articles_path %> |
对于每一个comment,这将会跳转到局部文件 app/views/comments/_comment.html.erb,而@article.comments是一个数组集合。作为跳转的方法会逐个迭代@article.comments的数组集合,对于每一个comment都赋值一个本地变量,名称都是同一个局部文件,在这个例子中comment在稍后可以使用,会给我们显示出结果来。
original text: http://guides.rubyonrails.org/getting_started.html#refactoring