Ruby on Rails: How do you explicitly define plural names and singular names in Rails?

Ruby on-RailsRuby

Ruby on-Rails Problem Overview


For example, I'm using "Bonus" as my model, so I'd expect "bonuses" to be the plural form and "bonus" to be the singular form.

However, in Ruby, this results in:

"bonus".pluralize # bonus
"bonuses".singularize # bonuse

So, when I do a "has_many :bonuses", for example, it doesn't use the Bonus.rb model (since Ruby expects a Bonuse.rb model instead). Is there a way to correct that in Ruby on Rails somehow such that "bonuses" acts as the plural form for the model bonus.rb?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

In config/initializers, you will find a file called inflections.rb. There are some instructions in here, but you will want something along the lines of:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'bonus', 'bonuses'
end

Solution 2 - Ruby on-Rails

Just to back up bcarlso, more on Inflector can be found here:

http://4loc.wordpress.com/2009/04/09/inflector-rails-pluralization/

Note that the position of the Inflector.inflections block is important and, as noted in the link reference, must be after the Initializer.run block.

Solution 3 - Ruby on-Rails

I believe you use the Inflector in your environment.rb (memory's a bit sketchy though) If I remember correctly you put it in a block

Inflector.inflections { | i | i.irregular 'bonus', 'bonuses' }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsjscView Question on Stackoverflow
Solution 1 - Ruby on-RailsPeter BrownView Answer on Stackoverflow
Solution 2 - Ruby on-RailsWarrenView Answer on Stackoverflow
Solution 3 - Ruby on-RailsbcarlsoView Answer on Stackoverflow