content_tag_for Rails中的集合?

时间:2010-06-01 09:22:23

标签: ruby-on-rails

我有一个Post模型。帖子有很多评论。我想使用<ul>post.comments生成content_tag_for元素。

理想情况下,它会产生

<ul id="comments_post_7" class="comments">  
...  
</ul>

其中7是帖子的ID。

我最接近的用途

<% content-tag-for :ul post, :comments do %>

产生

<ul id="comments_post_7" class="post">  
...  
</ul>

class="post"外,非常接近。在:class => :comments中使用content_tag_for会产生class="post comments",但我只想要class="comments"

我能够使用像

这样的东西似乎是合乎逻辑的
<% content_tag_for :ul post.comments do %>

但遗憾的是,产量

<ul id="array_2181653100" class="array">  
...  
</ul>

我搜索得很远。我觉得我错过了一些优雅的方式来做到这一点。我呢?因为,严重的是,<ul id="comments_post_<%= post.id %>" class="comments">是痛苦的。

2 个答案:

答案 0 :(得分:2)

您可以使用以下选项:id和:class

<% content_tag_for(:ul, post.comments, :id => "comments_post_#{post.id}", :class => "comments") do %>
  xxx
<% end %>

答案 1 :(得分:0)

我会通过扩展@ shingara的答案来做到这一点: 在posts_helper.rb中:

module PostsHelper
#This is specific only to your posts controller and only for your case!! 
#This can be made more generic though!

 def generate_ul(content)
   content_tag(:ul, content, :class => "comments", :id => "comments_post_#{post.id}")
 end
end

在您的观点中:

<%=h generate_ul(post.comments) %>