Ruby on Rails and Active Record Naming Conventions

Instead of thicc thighs saving lives, in Ruby, Active Record fulfills that role. Active Record is an ORM (Object Relational Mapping) layer that Ruby on Rails has. It allows users to bind the tables of a database to the Ruby code that uses the database records. With Active Record Migration (basically a method that allows us to evolve our database in a consistent way, i.e. add new tables, columns, rows, etc.), Ruby method names are automatically generated from the names of database tables.

By convention, table names are always plural while the names of methods are the singular version of the table’s name. For example, if we create a table named “whips” and migrate it, Active Record will automatically create a method called “whip.” So why is this important? Active Record uses the names to figure out how the mapping between models and databases look like/how it should be made. Meanwhile, Rails pluralizes the model class name to find the table — we’ve come full circle!

If the model class name contains multiple words, we have to write it in CamelCase, i.e. with the first letter of each word capitalized and no spaces; if the table name contains multiple words, we write it in snake_case, i.e. with underscores separating words. This is strict because Ruby is a “convention over configuration” language — if you follow the naming rules, you don’t have to write as much code. (The long answer is that, for most ORM frameworks, you need to write a lot of configuration code. However, the developers of Ruby hard coded and mapped out pathways so that, as long as you follow their naming conventions, you’re golden.)

Sometimes though Rails FAILS when it comes to English — pluralizing words can be hard. For example, Rails doesn’t know that the plural form of “bonus” is “bonuses” — it thinks its bonuse. Luckily, there are ways to correct incorrect inflections. In you config folder, there is a file called initializers/inflections.rb. There you can customize the pluralizations of particular words.

ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular '<singular>', '<plural>'
end

Some other words like “equipment” cannot be pluralized. What do you do then? Well, it’s the same thing. In the inflections file, you can mark that word as “uncountable.”

ActiveSupport::Inflector.inflections do |inflect|
inflect.uncountable 'equipment'
end

Make sure to add the new rules to the top! That way, the new rules will run before other rules load.

In short, Ruby on Rails coupled with Active Record is a really developer friendly programming language. There are so many hard coded methods we can tap into just by following some default naming conventions. It’s not an infallible program though, so sometimes we have to go in to the code and teach it proper english.

Published by runningtofu333

NYC, 28.

Leave a comment