简体   繁体   中英

Search and convert a substring into a link. Rails

We have this string: "according to posts #4,#5 and #6 the word..."

I want to convert the "#4", "#5" and the "#6" to links, using the link_to helper (the numbers are ids of a Model)

How can I do this? Is this difficult? Thank you in advance.

"posts #4,#5 and #6".gsub(/(\#\d+)/) { |s| 
    link_to s, :controller => :word, :action => :show, :id => s[1,10].to_i
}

Good candidate for a helper method:

def link_ids(string)
  string.gsub(/#(\d+)/) do
    link_to "##{$1}", mymodel_path($1)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM