简体   繁体   English

搜索并将子字符串转换为链接。 滑轨

[英]Search and convert a substring into a link. Rails

We have this string: "according to posts #4,#5 and #6 the word..." 我们有这个字符串:“根据帖子#4,#5和#6这个单词...”

I want to convert the "#4", "#5" and the "#6" to links, using the link_to helper (the numbers are ids of a Model) 我想使用link_to助手将“#4”,“#5”和“#6”转换为链接(数字是Model的ID)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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