Method: ActiveRecord::ModelSchema::ClassMethods#table_name
- Defined in:
- lib/active_record/model_schema.rb
#table_name ⇒ Object
Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
Nested classes are given table names prefixed by the singular form of the parent’s table name. Enclosing modules are not considered.
Examples
class Invoice < ActiveRecord::Base
end
file class table_name
invoice.rb Invoice invoices
class Invoice < ActiveRecord::Base
class Lineitem < ActiveRecord::Base
end
end
file class table_name
invoice.rb Invoice::Lineitem invoice_lineitems
module Invoice
class Lineitem < ActiveRecord::Base
end
end
file class table_name
invoice/lineitem.rb Invoice::Lineitem lineitems
Additionally, the class-level table_name_prefix
is prepended and the table_name_suffix
is appended. So if you have “myapp_” as a prefix, the table name guess for an Invoice class becomes “myapp_invoices”. Invoice::Lineitem becomes “myapp_invoice_lineitems”.
You can also set your own table name explicitly:
class Mouse < ActiveRecord::Base
self.table_name = "mice"
end
Alternatively, you can override the table_name method to define your own computation. (Possibly using super
to manipulate the default table name.) Example:
class Post < ActiveRecord::Base
def self.table_name
"special_" + super
end
end
Post.table_name # => "special_posts"
102 103 104 105 |
# File 'lib/active_record/model_schema.rb', line 102 def table_name reset_table_name unless defined?(@table_name) @table_name end |