28

Not sure why this has decided to stop working.

customers_controller.rb

redirect_to customers_url,
            notice: pluralize(@imported_customers.size, "customer") + " imported!"

And I'm getting the error:

NoMethodError: undefined method 'pluralize' for #CustomersController:0x007f3ca8378a20

Any idea where to start looking?

Wes Foster
  • 8,770
  • 5
  • 42
  • 62

3 Answers3

50

If you don't want to use view helpers, then you can use String#pluralize:

"customer".pluralize(@imported_customers.size)

If you want to use view helpers then you should include the respective helper as another answers or just use ActionView::Rendering#view_context:

view_context.pluralize(@imported_customers.size, "customer")
Aguardientico
  • 7,641
  • 1
  • 33
  • 33
  • Aha! I didn't realize `String` had a pluralize method. I chose this answer because it doesn't involve me bringing view helpers into the controller. Thanks! – Wes Foster Nov 14 '15 at 12:41
  • It's worth being clear that this is not a native Ruby method, rather `String#pluralize` is a method that Rails monkeypatches onto the `String` class. – David Runger Nov 14 '15 at 15:42
  • Also worth noting that unlike `pluralize`, using `"Customer".pluralize` will not return the number as well as the String. `pluralize( 2, "Customer" )` returns "2 Customers" where as `"Customer".pluralize( 2 )` returns "Customers". – Joshua Pinter Mar 13 '20 at 18:42
14

By default, the pluralize method is only made available in your views. To use it in a controller, put this at the top of your controller class:

include ActionView::Helpers::TextHelper

like

# app/controllers/cutomers_controller.rb

class CustomersController < ApplicationController
  include ActionView::Helpers::TextHelper

  def index
  etc. ...
David Runger
  • 765
  • 6
  • 13
13

You can call pluralize helper with:

ActionController::Base.helpers.pluralize(@imported_customers.size, "customer") + " imported!"

or

# app/controllers/cutomers_controller.rb

class CustomersController < ApplicationController
  include ActionView::Helpers::TextHelper
akbarbin
  • 4,985
  • 1
  • 28
  • 31