How to determine table name within a Rails 3 model class

后端 未结 3 2035
孤独总比滥情好
孤独总比滥情好 2021-02-18 16:22

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 `ta

相关标签:
3条回答
  • 2021-02-18 16:45

    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

    0 讨论(0)
  • 2021-02-18 16:49

    Found it.

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

    self.class.table_name
    
    0 讨论(0)
  • 2021-02-18 17:00

    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
    
    0 讨论(0)
提交回复
热议问题