I have a small encyclopedia of articles with my Article.rb:
class Article < ActiveRecord::Base
attr_accessible :name, :content
end
I now want to automatically link within the articles if I find text in one article that corrisponds to the name of another article. E.g. in the article named “Example One” the content is “You can also check Example Two for further reading.” On save of “Example One” I want to set a link to the article “Example Two”. My approach is to add to 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
My articles_controller is:
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
redirect_to admin_path
else
render 'edit'
end
end
But obviously there is an error refering to the line content = content.gsub(etc…):
NameError in ArticlesController#update
undefined local variable or method `article’ for #
How can I fix this so that it checks all other article names and creates the links for the current article I want to save?
Your changelink method does not “know” what is the article variable. You have to pass it as an argument:
But this way to implement links instead of the Articles’ name is not the best in my opinion.