views:

66

answers:

2

I have a Post model. Posts have many Comments. I want to generate a <ul> element for post.comments using content_tag_for.

Ideally, it'd produce

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

where 7 is the ID of the Post.

The closest I can get uses

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

which produces

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

which is pretty close, except for the class="post". Using :class => :comments in the content_tag_for yields class="post comments", but I just want class="comments".

It seems logical that I'd be able to use something like

<% content_tag_for :ul post.comments do %>

but, sadly, that yields

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

I've searched far and wide. I feel like I'm missing some elegant way to do this. Am I? Because, seriously, <ul id="comments_post_<%= post.id %>" class="comments"> is painful.

A: 

You can use option of :id and :class

<% content_tag_for(:ul, post.comments, :id => "comments_post_#{post.id}", :class => "comments") do %>
  xxx
<% end %>
shingara
Thanks. I suppose this is a reasonable compromise. Still disappointed that I have to resort to this, though.If I find myself using this pattern in other places, I'll probably factor it out into a helper as Shripad suggests below.
Nick
A: 

I would do this by extending @shingara's answer: in the 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

In your views:

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