Create a list of clickable links in a Helper module

638 views Asked by At

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?

4

There are 4 answers

0
Nitin Jain On BEST ANSWER

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
0
Fellow Stranger On

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
1
Richard Peck On

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

0
Igor Kasyanchuk On

You use this code

 def directory(links)
    links.inject([]) {|_, e| _ << link_to e.name, e.address; _ }.join.html_safe
 end