有没有一种方法可以在模型中使用pluralize()而不是视图中使用?

39

看起来pluralize只能在视图中使用,我的模型是否有办法也使用pluralize呢?

5个回答

72

我不想扩展东西,就只是这样:

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

希望这能帮助到其他人!


2
非常有帮助。这种情况通常只会在模型或控制器中出现一次。何必增加一行代码,当可以一次性完成呢! - sscirrus
我建议这样做,除非你真的需要在模型中使用视图助手(你可能不应该这样做)。如果你只是在顶部包含ActionController::Base.helpers,那么pluralize被引入的位置就不太明显,并且会在未来造成混淆。这样做也会包含所有其他的助手。我怀疑那里会有性能损失,但肯定会有代码异味。 - Joshua Pinter

59

将以下内容添加到您的模型中:

include ActionView::Helpers::TextHelper

如果我想在所有模型中添加它,有什么快速的方法吗? - coorasse
@coorasse 将其添加为所有模型继承的基本模型。 - Joshua Pinter
不要在模型中添加很多不需要的方法,可以查看下面@Tom Rossi的答案。更好的方法。 - iGEL

17

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

app/helpers/text_helper.rb

module TextHelper                       
  extend ActionView::Helpers::TextHelper
end                                     

应用程序/模型/任意模型.rb

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

在模型中包含ActionView::Helpers::TextHelper是可以的,但这样会使你的模型充斥着很多不必要的帮助方法。

而且,使用这种方法时,很难清楚地知道复数形式是从哪里来的。而TextHelper.pluralize则更加明确。

最后,你不需要在每个想要使用复数形式的模型中添加include;你可以直接在TextHelper上调用它。


4

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

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

并以这种方式调用

City.pluralize("ruby")
=> "rubies"

4
你所建议的已经被包含在String中,比如"ruby".pluralize。我认为问题涉及到ActionView::Helpers::TextHelper中的pluralize(number, word)方法。 - Edward Anderson
谢谢。正是我所需要的 :) - Kesha Antonov
这不是在视图中使用的同一个复数帮助程序。请参见@Sam Ruby的答案。 - aceofspades

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接