2013-01-21 49 views
-1

我有篇小百科全书我Article.rb:多GSUB

class Article < ActiveRecord::Base 
    attr_accessible :name, :content 
end 

我现在想在文章内自动链接,如果我发现在corrisponds至名一文文本另一篇文章。例如。在名为“Example One”的文章中,内容是“您还可以检查示例二进一步阅读。”在“示例一”的保存中,我想设置一个链接到文章“示例二”。我的方法是添加到Article.rb

class Article < ActiveRecord::Base 
    attr_accessible :name, :content 

    before_save :createlinks 

    def createlinks 
    @allarticles = Article.all 
    @allarticles.each do |article| 
     self.content = changelinks(self.content) 
    end 
    end 

    def changelinks(content) 
    content = content.gsub(/#{article.name}/, "<%= link_to '#{article.name}', article_path(article) %>") 
    end 

我articles_controller是:

def update 
    @article = Article.find(params[:id]) 
    if @article.update_attributes(params[:article]) 
    redirect_to admin_path 
    else 
    render 'edit' 
    end 
end 

但显然有错误指的行内容= content.gsub(等):

NameError在ArticlesController#更新 未定义的局部变量或方法'文章”的#

我怎样才能解决这一问题,以便它检查所有其他文章名称并创建我想要保存的当前文章的链接?

回答

0

您的changelink方法并不“知道”什么是文章变量。你必须把它作为参数传递:

def createlinks 
    @allarticles = Article.all 
    @allarticles.each do |article| 
     self.content = changelinks(self.content, article) 
    end 
    end 

    def changelinks(content, article) 
    content = content.gsub(/#{article.name}/, "<%= link_to '#{article.name}', article_path(article) %>") 
    end 

但是这样一来,可实现链路,而不是文章的名字是不是在我看来是最好的。

+0

谢谢。该错误现在已经消失。总之内容没有改变,似乎gsub没有改变文章来创建链接。我试图找出可能是什么原因... – user929062

+0

确实,它在我将gsub合并到循环中之后起作用:self.content.gsub!(/#{article.name} /,“<%= link_to' #{article.name}',article_path(article)%>“) – user929062