39

It seems pluralize only works within a view -- is there some way that my models can use pluralize too?

Tom Rossi
  • 11,604
  • 5
  • 65
  • 96
jpw
  • 18,697
  • 25
  • 111
  • 187

5 Answers5

72

Rather than extend things, I just it like this:

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

Hope this helps someone else!

Tom Rossi
  • 11,604
  • 5
  • 65
  • 96
  • 2
    Very helpful. This sort of case often pops up just once in a model or controller. Why add a new line when it can be done in one go! – sscirrus Sep 23 '14 at 23:09
  • I'd recommend doing this unless you really need view helpers all over your model (which you probably shouldn't). If you just include `ActionController::Base.helpers` at the top, it's less obvious where `pluralize` is being pulled in from and cause confusion in the future. You're also included all the other helpers by doing that. I doubt there's a performance loss there, but certainly a code smell. – Joshua Pinter Jan 03 '18 at 05:38
59

Add this to your model:

include ActionView::Helpers::TextHelper
Sam Ruby
  • 4,270
  • 22
  • 21
17

My favorite way is to create a TextHelper in my app that provides these as class methods for use in my model:

app/helpers/text_helper.rb

module TextHelper                       
  extend ActionView::Helpers::TextHelper
end                                     

app/models/any_model.rb

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

Including ActionView::Helpers::TextHelper in your models works, but you also litter up your model with lots of helper methods that don't need to be there.

It's also not nearly as clear where the pluralize method came from in your model. This method makes it explicit - TextHelper.pluralize.

Finally, you won't have to add an include to every model that wants to pluralize something; you can just call it on TextHelper directly.

Edward Anderson
  • 13,591
  • 4
  • 52
  • 48
4

YOu can add a method like this in your model

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

and call it in this way

City.pluralize("ruby")
=> "rubies"
Mattia Lipreri
  • 953
  • 1
  • 16
  • 30
0

This worked for me in rails 5.1 (see 2nd method, first method is calling it.)

# 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
t j
  • 7,026
  • 12
  • 46
  • 66
random_user_0891
  • 1,863
  • 3
  • 15
  • 39