lzap
lzap

Reputation: 17174

How to determine table name within a Rails 3 model class

I want to get table name in a model method. I found there should be method table_name but when I try to call it I get NameError Exception: undefined local variable or method `table_name'. It is obviously not there:

 pp methods.grep(/^ta.*/)
["table_name_prefix?",
 "table_name_suffix?",
 "taint",
 "taguri",
 "taguri=",
 "tainted?",
 "table_name_prefix",
 "table_name_suffix",
 "tap"]

How to get a "real" table name (no lowecase - pluralize tricks)?

Thanks

Upvotes: 22

Views: 20792

Answers (3)

erroric
erroric

Reputation: 1011

If you are in a class method of the class you want the table name for, try:

class Model < ActiveRecord::Base
  def self.class_method
    puts self.table_name
  end
end

If you try using

self.class.table_name

you'll run into a NoMethodError: undefined method 'table_name' for Class:Class

Upvotes: 0

lzap
lzap

Reputation: 17174

Found it.

It's a class method. Its not so obvious from the Rails 3 documentation.

self.class.table_name

Upvotes: 19

Mischa
Mischa

Reputation: 43298

But I need that information in the model's instance method. How to get it?

You can simply do this in your instance method:

class Model
  def instance_method
    puts Model.table_name
  end
end

Upvotes: 32

Related Questions