-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#更新 未定義的局部變量或方法'文章」的#
我怎樣才能解決這一問題,以便它檢查所有其他文章名稱並創建我想要保存的當前文章的鏈接?
謝謝。該錯誤現在已經消失。總之內容沒有改變,似乎gsub沒有改變文章來創建鏈接。我試圖找出可能是什麼原因... – user929062
確實,它在我將gsub合併到循環中之後起作用:self.content.gsub!(/#{article.name} /,「<%= link_to' #{article.name}',article_path(article)%>「) – user929062