我的发现者很疯狂.(.find返回错误的类?)

use*_*110 3 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

Rails 3.2.11 MySql2 Gem

嗨,有没有人知道为什么我的find方法返回错误类型的activerecord?

这是模型:

class NameList < ActiveRecord::Base
  attr_accessible :name, :selected, :type
  self.table_name='name_lists'
end  
Run Code Online (Sandbox Code Playgroud)

这是控制台输出:

>> k=NameList.find(28)
NameList Load (0.0ms)  SELECT `name_lists`.* FROM `name_lists` WHERE `name_lists`.`id` = 28 LIMIT 1
#<Neighborhood id: 28, name: "Bayview">

>> k.class
Neighborhood(id: integer, city_id: integer, name: string, street_count: integer,  relative_value: float, home_count: integer, min_lot_size: integer, created_at: datetime, updated_at: datetime)
Run Code Online (Sandbox Code Playgroud)

请注意,我正在调用NameList.find,但我得到的是Neighborhood对象.奇怪的是,sql似乎是正确的 - 它查询NameList表.

邻居对象没有什么特别之处:这是模型:

class Neighborhood < ActiveRecord::Base
  belongs_to :city
  has_many :streets
  attr_accessible :name, :relative_value, :street_count
  def self.make(name, relative_value, min_lot_size, street_count, home_count)
     n=Neighborhood.new
     n.name = name
   end
 end
Run Code Online (Sandbox Code Playgroud)

当我尝试保存它时 - 它使用了邻居模式的定义并尝试更新错误的表.

> k.name = "Foo"
"Foo"

>> k.save
(1.0ms)  BEGIN
(0.0ms)  UPDATE `neighborhoods` SET `name` = 'Foo', `updated_at` = '2013-03-14 17:40:46' WHERE `neighborhoods`.`id` = 28
(0.0ms)  COMMIT
 true
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

bou*_*der 6

您偶然发现了Rails单表继承(STI),如果向表中添加"类型"列,则会立即获得该表.本质上,该对象是从名称与该记录中的type列的值匹配的类中实例化的.

如果您想了解STI,请在此处阅读,查找Single Table Inheritance部分.在你的情况下,我打赌你并不真的想要这种行为,所以你的解决方案是将列重命名为类,类别或任何对你有意义的东西