0

A user has a set of saved links.

Each link has the properties address and text. These can be accessed like so:

@user.links.first.address
@user.links.first.text

How would I generate a list of a tags for all links that a user has saved in a helper method, that I can call from a view?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

4 Answers4

2

you can try with

def create_links
 html=""
 @user.links.each do |link|
  html += link_to "Link for #{link.address}", "#"
  html += link_to "Link for #{link.text}", "#"
 end
  html.html_safe
end
Nitin Jain
  • 3,053
  • 2
  • 24
  • 36
1

Why don't you just do a .each on the @user.links?

You could do this:

<% @user.links.each do |link| %>
    <%= link_to link.text, link.address %>
<% end %>

This would negate the requirement of loading a helper

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • It's true that this would normally be the "easiest" way to go. In my case I have conditionals involved in the loop which would clutter the view a bit too much, hence why I'd like to use a helper. – Fellow Stranger Dec 27 '13 at 01:36
1

You use this code

 def directory(links)
    links.inject([]) {|_, e| _ << link_to e.name, e.address; _ }.join.html_safe
 end
Igor Kasyanchuk
  • 766
  • 6
  • 12
0

Perhaps I expressed myself not clearly enough, because both answers uses link.address and link.text in a way I don't quite understand. But it gave me enough info to solve it myself. This is how I did it:

def link_generator(user_links)
  html = ""
  user_links.each do |link|
    html += link_to link.name, link.address
  end
  html.html_safe
end
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232