【问题标题】:Rails : Using helper method (ActionView::Helpers::DateHelper) inside ActiveSupport::Concern for modelRails:在模型的 ActiveSupport::Concern 中使用辅助方法 (ActionView::Helpers::DateHelper)
【发布时间】:2023-01-20 02:33:45
【问题描述】:

我正在尝试在最终包含在模型中的 Rails 关注点中使用 ActionView::Helpers::DateHelper 中的 l 方法。

我有这个问题:

module SessionSupport
  extend ActiveSupport::Concern
  include ActionView::Helpers::DateHelper
  def dates_presenter
        "#{l(start_date, format: :short)} - #{l(end_dates, format: :short)}}"
  end
end

但是,然后我得到 NoMethodError - undefined method l' for InstanceFromModelInWhichConcernIsIncluded`

如何在模型关注点内使用辅助方法?

【问题讨论】:

    标签: ruby-on-rails include helper activesupport-concern


    【解决方案1】:

    创建您的 Rails 辅助方法

    def l(val, opts = {})
       return nil unless val.present?
       value = val.to_date if val.is_a? String
       super(val, opts)
    end
    

    或者

    module SessionSupport
      extend ActiveSupport::Concern
      include ActionView::Helpers::DateHelper
      def dates_presenter
            "#{I18n.l(start_date, format: :short)} - #{I18n.l(end_dates, format: :short)}}"
      end
    end
    

    I18n API 最重要的方法是:

    translate # Lookup text translations
    localize  # Localize Date and Time objects to local formats
    

    它们具有别名#t 和#l,因此您可以像这样使用它们:

    I18n.t 'store.title'
    I18n.l Time.now
    

    【讨论】:

      猜你喜欢
      • 2013-12-06
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2013-05-26
      • 2014-04-28
      • 1970-01-01
      相关资源
      最近更新 更多