ruby · level 3 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three models, one exception. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Model
def self.table_name(custom = nil)
@table_name = custom if custom
@table_name || "#{name.downcase}s"
end
end
class Recipe < Model
end
class Mouse < Model
table_name "mice"
end
class Cat < Model
end
p [Recipe.table_name, Mouse.table_name, Cat.table_name]
your turn
Your turn. Give every model a default primary key.
Make id the default primary key in the first blank. Then give countries their own key in the second, such as code.
fix it
People end up in a table called persons. Fix it.
- Person was set to people, yet it says persons. What happens to
@table_namewhen you calltable_namewith no argument? - Line 3 stores
customevery time, so a plain call wipes the setting withnil. - Only store it when one is given:
@table_name = custom if custom.
nailed it
you let the names do the work. :D
- A convention is a default worked out from names.
- Configure only the cases that break the pattern.
- Class-level settings live in each class's own
@variables.
new words in your collection
- convention
- convention over configuration
This lesson isn’t saved. A free account remembers every lesson you finish.