是否有任何宝石允许用特定格式替换字符串以链接到某些带参数的控制器?
示例:在文章/文章/ 2 /第二篇文章的内容中,我想链接到上一篇文章/ articles / 1 / first-article。
由于
答案 0 :(得分:0)
没有“宝石”,但您可以在模型中轻松完成此操作。
class Article
def next
self.class.where("id > ?", id).first
end
def previous
self.class.where("id < ?", id).last
end
end
然后你可以在你的控制器中使用它们:
@article = Article.find(params[:id])
@next_article = @article.next
@previous_article = @article.previous
答案 1 :(得分:0)
确定,
我为此写了一个帮手:
module ApplicationHelper
def raw_with_links(text)
text.gsub! /{'(.+?)', (.+?)(,(.+?))*}/ do |full_match|
# The expression returned from this block will be used as the replacement string
# $1 will be the matched content between the ' and ' quotes.
# $2 will be the mathed content in the second group with the route name
#4 will be the matched content in the last group with route parameters, if any
url = Rails.application.routes.url_helpers.send $2, $4
link = "<a href=\"" + url + "\">" + $1 + "</a>"
end
raw(text)
end
end
然后你可以在这样的视图中调用它:
<%= raw_with_links @article.content %>
以下是如何在文本中创建链接(路由参数(示例中的值7)不是强制性的):
class HomeController < ApplicationController
def index
@article.content = "<p>This is the article content with the {'link', other_route_name_path, 7} to the other route.</p>"
end
end
,结果是(考虑到路线other_route_name
为other_route/:id
:
<p>This is the article content with the <a href="other_route/7">link</a> to the other route.</p>