Graeme
Graeme

Reputation: 481

Using link_to in Rails 3 on the end of a string

There is probably a really simple answer to this but, as I'm a Rails newbie, I'm having great difficulty identifying the appropriate syntax.

Basically, I want to display a string with a link on the end, in which "Jimmy" here represents both the individual record and the link to that record:

"This video was posted by Jimmy"

I'd like to create a local variable to store the string, so my initial thought was to create the variable as follows:

my_string = "This video was posted by " + (link_to user.name, user)

However, this doesn't appear to work. Instead, it simply displays the generated HTML in the browser, i.e.:

This video was posted by <a href="/users/6">Jimmy</a>

This isn't what I want - I obviously want it to display:

This video was posted by Jimmy

in which Jimmy is the link.

Any ideas? I've tried adding .html_safe to the end of the string, but that doesn't work.

Thanks!

Upvotes: 0

Views: 1050

Answers (3)

Jack Franklin
Jack Franklin

Reputation: 3765

A much easier way to do this would be:

<td>Video created by <%= link_to user.name, user %></td>

No need to use string concatenation or use <%= "Video created by" %>, there's no need to run that through the Ruby parser, just use the plain text version :)

Upvotes: 3

Graeme
Graeme

Reputation: 481

Thanks for your help! I managed to fix the issue without needing to declare a variable (I was trying to be too clever).

The final (elided) code, in case anyone is interested, is as follows (in a table cell):

<td><%= "Video created by " %><%= link_to user.name, user %></td>

As always, it turns out the code is much easier to apply once you know how :-)

Thanks again!

Upvotes: 0

deefour
deefour

Reputation: 35370

Check out raw

<%= raw my_string %>

Though, assuming this is in your view, I don't know why you'd be storing this to some my_string variable.

<span>This video was posted by <%= link_to user.name, user %></span>

Upvotes: 0

Related Questions