0

I am trying to add a link field to a form. The link should be clickable when displayed. When I run

rails generate migration AddLinkToThings link:xxxx

What should xxx be? I've tried link:string, but that just puts out a string, of course.

Here is how I am making the title of a Thing link to where the user specifies:

<strong><%= link_to @thing.title, @thing.link %></strong>

The problem is that @thing.link is linking to the show page for the Thing, and not the link that the user typed in. It's ultra confusing to explain.

For example, when I created this Thing, I linked it to google.com, but instead, it's linking to mywebsite.com/things/7. Hope this makes sense.

Dylan Richards
  • 708
  • 1
  • 13
  • 33

1 Answers1

1

It would be a string, but then you'd just use it inside of a link_to helper in your view.

Depending on the contents of the string, you may need to append .html_safe to the string inside the link_to tag.

Update

Based on your edit, I think you'll want to interpolate @thing.link inside a string.

Example:

<strong><%= link_to @thing.title, "#{@thing.link.try(:html_safe_}" %></strong>

If link will never be nil, you don't need the try.

CDub
  • 13,146
  • 4
  • 51
  • 68
  • Okay. That's worked. I'll update the question with a little problem that's occurring, though. – Dylan Richards Dec 03 '13 at 18:32
  • Awesome, but I'm getting "undefined method html_safe for nil:NilClass" Lol @CDub – Dylan Richards Dec 03 '13 at 18:40
  • `link` on `@thing` in that case is nil – CDub Dec 03 '13 at 18:41
  • @DylanRichards does `@thing.link` have a value? you should check for a value in your code or add a default value. – Austin Lin Dec 03 '13 at 18:42
  • I'll check for a value. Give me a second – Dylan Richards Dec 03 '13 at 18:46
  • Ah. Link does appear to be `nil` from the console. I think I have an old tutorial that will help me actually save the link when the Thing is created. I'll get back to you all if it doesn't work out. – Dylan Richards Dec 03 '13 at 18:48
  • Okay. I got the link to save on the creation of the Thing. But now when I click the link, it routes to www.mysite.com/things/www.google.com. What's this about? – Dylan Richards Dec 03 '13 at 18:52
  • 1
    Check out: http://stackoverflow.com/questions/16721816/how-do-i-defined-a-variable-link-to-to-an-external-url - if you're storing the URL without `http`, you need to prepend it to the string in the `link_to`, otherwise it treats it as a relative URL. – CDub Dec 03 '13 at 18:58