Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ActiveRecord infer mapping from singular (class) and plural (table); and is it possible to override?

How does ActiveRecord infer mapping from singular (class) and plural (table) for example:

People = Person
Ducks = Duck
Geese = Goose 
Categories = Category

Seems like a nice idea in concept, but no idea if I have to map the singular (class) and plural (table) instances, or if ActiveRecord is some how "magically" doing this. Plus, seems like this might lead to more overhead when having to pluralize a name that's not as simple as just adding "s".

NOTE: Moved the second part of this question here: Does ActiveRecord assign a key to every table using the naming convention “ID”, and if so, why?

like image 589
blunders Avatar asked Dec 12 '10 13:12

blunders


1 Answers

Rails uses the ActiveSupport::Inflector to keep track of words and how to change them. For example, Rails will know to store UserPreference in user_preferences

You can also add your one inflections to the inflector to handle weirder cases where adding an s does not make sense.

In /config/initializers/inflections.rb you get the following:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural /^(ox)$/i, '\1en'
  inflect.singular /^(ox)en/i, '\1'
  inflect.irregular 'person', 'people'
  inflect.uncountable %w( fish sheep )
end

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html

like image 121
Jesse Wolgamott Avatar answered Nov 06 '22 07:11

Jesse Wolgamott