table_name

table_name()
Instance Public methods

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"
doc_ruby_on_rails
2015-06-20 00:00:00
Comments
Leave a Comment

Please login to continue.