Search code examples
ruby-on-railsactiverecordactiondispatch

Attr_reader for Active Record model attribute


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?!


Solution

  • 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