看起来pluralize
只能在视图中使用,我的模型是否有办法也使用pluralize
呢?
看起来pluralize
只能在视图中使用,我的模型是否有办法也使用pluralize
呢?
我不想扩展东西,就只是这样:
ActionController::Base.helpers.pluralize(count, 'mystring')
希望这能帮助到其他人!
将以下内容添加到您的模型中:
include ActionView::Helpers::TextHelper
我的最喜欢的方法是在应用程序中创建一个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上调用它。
您可以在您的模型中添加像这样的方法:
def self.pluralize(word)
ActiveSupport::Inflector.pluralize(word)
end
并以这种方式调用
City.pluralize("ruby")
=> "rubies"
这个方法对我在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
ActionController::Base.helpers
,那么pluralize
被引入的位置就不太明显,并且会在未来造成混淆。这样做也会包含所有其他的助手。我怀疑那里会有性能损失,但肯定会有代码异味。 - Joshua Pinter