【问题标题】:Attr_reader for Active Record model attribute用于 Active Record 模型属性的 attr_reader
【发布时间】:2014-12-09 01:38:36
【问题描述】:
Article.rb < ActiveRecord::Base   
... 

attr_reader :title

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

end

我正在尝试覆盖每篇文章标题的显示方式,因为如果我不这样做,它看起来很难看,但我不断收到如下错误:

SystemStackError in ArticlesController#index or StackLevelTooDeep

我不确定如何解决这个问题。如果我将方法更改为 ntitle 之类的不同方法,它将起作用。为什么?!

【问题讨论】:

    标签: ruby-on-rails activerecord actiondispatch


    【解决方案1】:

    当您在def title 中调用self.title 时,它会调用自身,因此您会得到无限递归,并导致错误StackLevelTooDeep

    这应该可行:

    class Article < ActiveRecord::Base
      ...
    
      def title
        read_attribute(:title).to_s.gsub(?", " ")
      end
    
    end
    

    【讨论】:

    • 非常感谢。不敢相信我是在内部调用它。非常感谢
    猜你喜欢
    • 2016-07-20
    • 1970-01-01
    • 2012-05-18
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多