视图的帮助程序存储在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 %> |
本文介绍了一种在Ruby on Rails应用中使用视图帮助程序的方法。通过创建PostsHelper并定义join_tags方法,实现了将Post模型中的多个标签名以逗号分隔的形式展示。这种方法不仅提高了代码的复用性,还简化了视图文件。
14

被折叠的 条评论
为什么被折叠?



