视图的帮助程序存储在app/helpers目录下。它提供短小可以重复利用的代码。
在我们的例子中,我们想有一个方法可以将所有对象的name属性用逗号连接起来。
因为这是为post显示服务的。所以把代码放在PostsHelper。
打开app/helpers/posts_helper.rb添加下面的代码
module PostsHelper def join_tags(post) post.tags.map { |t| t.name }.join(", ") end end
现在我们可以编辑app/views/posts/show.html.erb
<p class="notice"><%= notice %></p> <p> <b>Name:</b> <%= @post.name %> </p> <p> <b>Title:</b> <%= @post.title %> </p> <p> <b>Content:</b> <%= @post.content %> </p> <p> <b>Tags:</b> <%= join_tags(@post) %> </p> <h2>Comments</h2> <%= render @post.comments %> <h2>Add a comment:</h2> <%= render "comments/form" %> <%= link_to 'Edit Post', edit_post_path(@post) %> | <%= link_to 'Back to Posts', posts_path %> |