ruby on rails - How to autolink all words in a rendered text that match an item name in my database? -


i have rails app postgres database articles , items. whenever render text article, can somehow scan text , if finds word matches name of item in database autolinks items show_path.

any ideas? appreciated.

you can reason out first principles.

make little method returns either word, or link article if word in article.

def make_link(word)   item = item.find_by(text: word.downcase)   item ? link_to(word, item_path(item_id) : word end 

now, map words in article using method above convert linkable ones links.

new_article = actioncontroller::base.helpers.sanitize(article).split(' ').map{|word| make_link(word)}.join(' ').html_safe 

note html_safe method ensure link tags aren't escaped when new_article rendered, , sanitize method ensure unwanted html tags in source removed.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -