×

ruby · level 3 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

over configuration: work it out from the name.

A Rails model called Order is stored in a table called orders, and other tables point at it with order_id. Nobody wrote that down. It follows a convention, an agreed way of naming things.

means sensible defaults are worked out from names, so you only write settings when you break the pattern. Here name gives a class's name as text, and table_name "people" configures the one model whose plural is not a plain s.

class Model
  def self.table_name(custom = nil)
    @table_name = custom if custom
    @table_name || "#{name.downcase}s"
  end
end
class Order < Model
end
class Person < Model
  table_name "people"
end
puts Order.table_name
puts Person.table_name

Inside a class method, @table_name belongs to that one class, so Order and Person each keep their own.