如何在model里使用view helper 博客分类: Ruby On Rails actionviewhelpersactiverecord
程序员文章站
2024-03-19 21:01:16
...
class Glosentry < ActiveRecord::Base include ActionView::Helpers::TextHelper def short_explanation(len=20) truncate(self.explanation, len) end end
上面的方法虽然可以用但,逻辑上并不好,因为Model不是helper,所以可以用下面的方法
class Glosentry < ActiveRecord::Base class GlosentryHelper include ActionView::Helpers::TextHelper end def helper @h ||= GlosentryHelper.new end def short_explanation(len=20) helper.truncate(self.explanation, len) end end
def method_missing(*args, &block) @h.send(*args, &block) end