有没有办法在模型内而不是视图中使用pluralize()?
-
25-10-2019 - |
题
它似乎 pluralize
仅在视图中起作用 - 我的模型可以使用某种方式 pluralize
也?
解决方案
将其添加到您的模型中:
include ActionView::Helpers::TextHelper
其他提示
我不是这样,而是这样:
ActionController::Base.helpers.pluralize(count, 'mystring')
希望这对别人有帮助!
我最喜欢的方法是在我的应用程序中创建一个Texthelper,该应用程序将这些作为用于我的模型中使用的类方法:
app/helpers/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上调用它。
您可以在模型中添加这样的方法
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
不隶属于 StackOverflow