Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

You use this code

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top