Attr_reader for Active Record model attribute

1.3k views Asked by At
Article.rb < ActiveRecord::Base   
... 

attr_reader :title

def title
    self.title.gsub(/"/," ")
end

end

I am trying to overwrite the way each articles title is displayed because it looks ugly if I don't but I keep getting an error like so:

SystemStackError in ArticlesController#index or StackLevelTooDeep

I am not sure how to remedy this problem. If I change the method to something different like ntitle, it will work. WHY?!

1

There are 1 answers

1
Pavel Evstigneev On BEST ANSWER

when you call self.title inside def title it call itself, so you get infinite recursion, and it cause error StackLevelTooDeep.

This should work:

class Article < ActiveRecord::Base
  ...

  def title
    read_attribute(:title).to_s.gsub(?", " ")
  end

end