ActiveRecord ignores table_name_prefix

陌路散爱 提交于 2019-12-12 04:48:58

问题


I've got situation where I need to define table_name and table_name_prefix within a model and for some reason table_name overrides table_name_prefix.

class ScheduleItem < ActiveRecord::Base
  self.table_name = "schedule_item"
  self.table_name_prefix = 'ACQ_IBM_T.'
end

The prefix is completely ignored in the queries. But, when I comment out the table_name part then the prefix is added. Anyone has seen strange behavior like this before?


回答1:


In ActiveRecord::ModelSchema::ClassMethods, the table_name setter puts the value in @table_name:

def table_name=(value)
  ...
  @table_name        = value

And the table_name getter just uses the @table_name value if it is defined:

def table_name
  reset_table_name unless defined?(@table_name)
  @table_name
end

The table_name_prefix is only used to help Rails when it is trying to guess the table name based on the class name (in reset_table_name).

If you have a table name that Rails can't guess, you can do this:

class ScheduleItem < ActiveRecord::Base
  self.table_name = "ACQ_IBM_T.schedule_item"

Or if you need to use the prefix somewhere else, you can do this:

class ScheduleItem < ActiveRecord::Base
  self.table_name_prefix = 'ACQ_IBM_T.'
  self.table_name = "#{table_name_prefix}schedule_item"


来源:https://stackoverflow.com/questions/29174840/activerecord-ignores-table-name-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!