简体   繁体   English

Rails:在 ActiveSupport::Concern 中使用辅助方法 (ActionView::Helpers::DateHelper) 用于 model

[英]Rails : Using helper method (ActionView::Helpers::DateHelper) inside ActiveSupport::Concern for model

I am trying to use the l method from ActionView::Helpers::DateHelper in a rails concern that is eventually included in a model.我正在尝试在最终包含在 model 中的 rails 关注中使用 ActionView::Helpers::DateHelper 中的l方法。

I have this in my concern:我有这个问题:

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

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

How can I use a helper method inside a model concern?如何在 model 问题中使用辅助方法?

Create your rails helper method创建您的 Rails 辅助方法

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

or或者

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

The most important methods of the I18n API are: I18n API 最重要的方法是:

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

These have the aliases #t and #l so you can use them like this:它们具有别名#t 和#l,因此您可以像这样使用它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM