wyc
wyc

Reputation: 55293

Using to_sentence in the following for each statement?

I have the following for each statement:

    <% @post.votes.each do |vote| %>
      <span class='voted-user'>
        <%= link_to vote.user.username, vote.user %>
      </span>
    <% end %>

I want to have the usernames like this:

username1, username2, username3, and username4 using the to_sentence method. But I'm not sure how to use it in this case. Any suggestions?

Upvotes: 1

Views: 229

Answers (2)

James
James

Reputation: 4807

<%= @post.votes.map do |vote| %>
  <% content_tag :span, :class => 'voted-user' do %>
    <% link_to vote.user.username, vote.user %>
  <% end %>
<% end.to_sentence.html_safe %>

Although I would suggest just moving it all into a helper.

view

<%= vote_links @post.votes %>

votes_helper.rb

def vote_links(votes)
  votes.map do |vote|
    content_tag :span, :class => 'voted-user' do
      link_to vote.user.username, vote.user
    end
  end.to_sentence.html_safe
end

Upvotes: 1

edgerunner
edgerunner

Reputation: 14973

You could use the map method instead of each to return an array and jon them using to_sentence. And use content_tag for the span to tidy it up.

<%= 
@post.votes.map do |vote| 
  content_tag :span class: 'voted-user' do
    link_to vote.user.username, vote.user
  end
end.to_sentence 
%>

Upvotes: 2

Related Questions