By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created.
Model | Table | Foreign key |
---|---|---|
Pokemon | pokemons | pokemon_id |
Move | moves | move_id |
PokemonMove | pokemon_moves | pokemon_move_id |
See Naming conventions for more details.
It allows you to write:
class Pokemon < ActiveRecord::Base
has_many :pokemon_moves
has_many :moves, through: :pokemon_moves
end
instead of:
class Pokemon < ActiveRecord::Base
self.table_name = 'pokemons'
has_many :pokemon_moves, class_name: 'PokemonMove', foreign_key: 'pokemon_id'
has_many :moves, through: :pokemon_moves, source: :move
end
By that, you should understand
pokemon.moves
as pokemon.pokemon_moves.map(&:move)
and
pokemon.pokemon_moves
as PokemonMove.where('pokemon_id = ?', pokemon.id)
.
In order to do that, we will need the following methods:
See Inflections for a complete reference.
Implement the ActiveRecord::Support::Inflector
class, run specs and play with the REPL.
Specs
make test
Playground
make play
Open lib/active-record/support/inflector.rb
, spec/active-record/support/inflector_spec.rb
and spec/data/inflections.json
.