37

它似乎pluralize只在视图中有效——我的模型是否也可以使用某种方式pluralize

4

5 回答 5

69

而不是扩展事物,我只是这样:

ActionController::Base.helpers.pluralize(count, 'mystring')

希望这对其他人有帮助!

于 2013-09-28T15:21:36.777 回答
59

将此添加到您的模型中:

include ActionView::Helpers::TextHelper
于 2011-07-24T12:06:20.120 回答
17

我最喜欢的方法是在我的应用程序中创建一个 TextHelper,将这些作为类方法提供给我的模型:

应用程序/帮助者/text_helper.rb

module TextHelper                       
  extend ActionView::Helpers::TextHelper
end                                     

应用程序/模型/any_model.rb

def validate_something
  ...
  errors.add(:base, "#{TextHelper.pluralize(count, 'things')} are missing")
end

在你的模型中包含 ActionView::Helpers::TextHelper 是可行的,但是你也会在你的模型中添加很多不需要的辅助方法。

在您的模型中,复数方法的来源也不太清楚。此方法使其显式 - TextHelper.pluralize

最后,您不必为每个想要复数的模型添加包含;你可以直接在 TextHelper 上调用它。

于 2012-12-07T15:40:13.130 回答
4

您可以在模型中添加这样的方法

  def self.pluralize(word)
    ActiveSupport::Inflector.pluralize(word)
  end

并以这种方式调用它

City.pluralize("ruby")
=> "rubies"
于 2011-07-24T15:44:52.980 回答
0

这在 rails 5.1 中对我有用(参见第二种方法,第一种方法是调用它。)

# gets a count of the users certifications, if they have any.
def certifications_count
  @certifications_count = self.certifications.count
  unless @certifications_count == 0 
    return pluralize_it(@certifications_count, "certification")
  end
end

# custom helper method to pluralize.
def pluralize_it(count, string)
  return ActionController::Base.helpers.pluralize(count, string)
end
于 2017-11-23T00:45:38.700 回答