yellowreign
yellowreign

Reputation: 3638

Showing Link in Text Field in Rails

In my Rails 3.1 app, I have a text field for comments and I want to be able to allow people to include clickable links (instead of just the url showing as plain text), as well as having the text field recognize when a user had line breaks in their text field (without the user adding html). How can I do this?

This works for showing a link if a user puts the html for a href: <%= simple_format(@user.description) %>

And this works for recognizing and displaying the line breaks from carriage returns in the text_field: <%= h(@user.description).gsub(/\n/, '<br/>').html_safe %>

However, I haven't figured out how to do both, together.

Upvotes: 3

Views: 3076

Answers (2)

BenKoshy
BenKoshy

Reputation: 35731

Use the Rinku Gem

Link is here.

It brilliantly solves the problem. Enjoy!

Upvotes: 0

Samiron
Samiron

Reputation: 5317

How about this?

#Doesnt work in this case
#<%= simple_format( h(@user.description).gsub(/\n/, '<br/>') ).html_safe %>

EDIT: Seems like you need auto_link function to achieve this. Though it is removed from rails 3.1 it is available as a gem. So if you are using rails 3.1 or later you need to get this from a separate gem

#in Gemfile
gem "rails_autolink", "~> 1.0.9"
#in application.rb
require 'rails_autolink'

#Run
bundle install

#now in you view use it like
<%= h auto_link(simple_format(text)) %>

auto_link not only converts urls but also email addresses in clickable link. Get the document here.

Reference Links:

Upvotes: 5

Related Questions