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
Post a Comment