75

I have a model named "clothing" which I want to be the singlular (one piece of clothing). By default, rails says the plural is clothings. Right or wrong, I think it will be more readable if the plural is "clothes".

How do I override the plural naming convention? Can I do it right in the model so I don't have to do it over and over? How will this change how routes are handled (I am using restful architecture)?

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
chrishomer
  • 4,900
  • 5
  • 38
  • 52

4 Answers4

129

I'm no RoR expert, but did find a possible approach. From the referenced site you can add inflection rule inside the config/initializers/inflections.rb file:

# Add new inflection rules using the following format 
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'clothing', 'clothes'
end
Paweł Gościcki
  • 9,066
  • 5
  • 70
  • 81
Rich Seller
  • 83,208
  • 23
  • 172
  • 177
  • 45
    Actually, your custom inflections should reside in config/initializers/inflections.rb – Aaron Rustad Jul 26 '09 at 22:58
  • 3
    For those who are lazy like me: `ActiveSupport::Inflector.inflections do |inflect|` if it doesn't find Inflector on it's own – Abe Petrillo Jan 29 '13 at 23:21
  • I like your approach. If I had many "custom" inflections, I would save them in a yaml and load the file in that same archive. – Aldana Apr 05 '16 at 00:28
  • 1
    If passed an optional locale, rules for other languages can be specified. If not specified, defaults to **:en** which will provide rules for english language. `ActiveSupport::Inflector.inflections(:en)` – Sree Raj Nov 21 '16 at 11:46
28

For rails 2.3.2 and maybe 2+, you need to do it a little different:

ActiveSupport::Inflector.inflections do |inflect|
    inflect.plural /^(ox)$/i, '\1\2en'
    inflect.singular /^(ox)en/i, '\1'

    inflect.irregular 'octopus', 'octopi'

    inflect.uncountable "equipment"
end
chrishomer
  • 4,900
  • 5
  • 38
  • 52
5

Add this in your environment.rb file if you are trying to stop database pluralization

ActiveRecord::Base.pluralize_table_names = false
j0k
  • 22,600
  • 28
  • 79
  • 90
Shan Valleru
  • 3,093
  • 1
  • 22
  • 21
-1

With Ruby 2.2.2 windows or linux for me best solve was :

ActiveRecord::Base.pluralize_table_names = false

class Persona < ActiveRecord::Base
end


personas = Persona.all
personas.each do | personita |
  print "#{personita.idpersona}   #{personita.nombre}\n"
end

p Persona.count
JAGJ jdfoxito
  • 747
  • 5
  • 5