Content_tag_for collections in Rails?

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

Ideally, this will create

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

where 7 is the message identifier.

The closest I can use

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

which produces

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

which is pretty close except class="post". Use :class => :commentsin content_tag_forgives class="post comments", but I just want to class="comments".

It seems logical that I can use something like

<% content_tag_for :ul post.comments do %>

but unfortunately we get

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

I have searched all over the world. I feel that I am lacking an elegant way to do this. I AM? Because, seriously, <ul id="comments_post_<%= post.id %>" class="comments">is painful.

+3
source share
2 answers

: id : class

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

, @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) %>
0

Source: https://habr.com/ru/post/1747954/


All Articles