私は Article.rb で記事の小さな百科事典を持っています:
class Article < ActiveRecord::Base
attr_accessible :name, :content
end
ある記事に別の記事の名前に対応するテキストが見つかった場合、記事内で自動的にリンクしたいと考えています。たとえば、「例 1」という名前の記事では、内容は「さらに読むために例 2 もチェックできます」です。「Example One」の保存時に記事「Example Two」へのリンクを設定したい。私のアプローチは、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
私の article_controller は次のとおりです。
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
redirect_to admin_path
else
render 'edit'
end
end
しかし明らかに、行 content = content.gsub(etc...) を参照するエラーがあります:
ArticlesController の NameError#update 未定義のローカル変数またはメソッド `article' for #
他のすべての記事名をチェックして、保存したい現在の記事へのリンクを作成するようにするにはどうすればよいですか?