Arw50452
Arw50452

Reputation: 325

Rails Display Link in Database Using link_to

In Rails, I have a "notifications" class, one field of which is "link". The links contained within this class are formatted like: exchange_path(6), where that is the path to the show action in the exchange controller.

I'm now trying to output this link as such:

<%= link_to "View Exchange", notification.link %>

This line is in a loop which begins as such:

<% @notifications.each do |notification| %>

When I click this link, it takes me to localhost:3000/users/exchange_path(6) instead of localhost:3000/exchanges/6 like I would expect. (The loop generating the faulty link is on localhost:3000/users/2)

Upvotes: 0

Views: 380

Answers (2)

Doon
Doon

Reputation: 20232

this could be scary...

<%= link_to "View Exchange", eval(notification.link) %>

should evaluate and use the path helpers. but you need to be 100% sure that nothing bad gets put in the link field..

Upvotes: 1

NM Pennypacker
NM Pennypacker

Reputation: 6952

You could do this:

<%= link_to("View Exchange", "/#{notification.link.gsub('(', '/').gsub(')', '').gsub('_path', 's')}") %>

or set up a method in your model that formats it for you:

def format_link
  link.gsub('(', '/').gsub(')', '').gsub('_path', 's')
end

and just call that in your link_to:

link_to("View Exchanges", notification.format_link)

This will only work if all the links are formatted exactly as the example in the question

Upvotes: 0

Related Questions