Reputation: 131
I am writing a helper method for my rails views. After evaluating each value in an array I want to output a button to the html. However, 'puts' is not working and 'return' will work only for one value and end the operator there only.
def show_power_buttons
levels = [1, 2, 3, 4, 5]
levels.each do |level|
count = @player.powers.where(level: level).count
if count > 0
puts (link_to level, '#', :class => 'btn btn-primary')
end
end
end
I know I am missing something very obvious but unable to figure it out.
Upvotes: 0
Views: 277
Reputation: 6100
each
returns array
on which you have called it, it does not return result of the block.
You can use map
to make this work
def show_power_buttons
levels = [1, 2, 3, 4, 5]
levels.map do |level|
count = @player.powers.where(level: level).count
(link_to level, '#', :class => 'btn btn-primary') if count > 0
end.compact.join('\n').html_safe
end
compact
will discard all nil
values, we then use join
because this is still array, you can join it or can use it this way and in your view
just say:
def show_power_buttons
levels = [1, 2, 3, 4, 5]
levels.map do |level|
count = @player.powers.where(level: level).count
(link_to level, '#', :class => 'btn btn-primary') if count > 0
end.compact # returns array of string that are links
end
<%= show_power_buttons.each do |pw| %>
<%= pw.html_safe %>
<% end %>
You have to use html safe, because it will convert string to html
Upvotes: 3
Reputation: 2901
Collect the return value and return it at the end of the method:
def show_power_buttons
levels = [1, 2, 3, 4, 5]
retval = []
levels.each do |level|
count = @player.powers.where(level: level).count
if count > 0
retval << link_to level, '#', :class => 'btn btn-primary'
end
end
return retaval
end
It will output the arrach of links.
Upvotes: 1