如何在model里使用view helper

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

你可能感兴趣的:(ActiveRecord,actionview,helpers)