假设我有模型
class Widget < ActiveRecord::Base
has_many :widget_spots
和
class WidgetSpot < ActiveRecord::Base
belongs_to :widget
此外,在我的 MySQL 表“widget_spots”中,我有一列“widget_id”
+--------------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| widget_id | int(11) | NO | PRI | NULL | |
................
+--------------------+------------+------+-----+---------+-------+
现在,如果在我的 rails 控制台中,尝试访问 widget_spot_ids 会出错。
> widget = widgets.find(:first)
> widget.widget_spot_ids
ActiveRecord::UnknownPrimaryKey: ActiveRecord::UnknownPrimaryKey
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/activerecord-3.1.1/lib/active_record/reflection.rb:374:in `primary_key'
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/activerecord-3.1.1/lib/active_record/reflection.rb:228:in `association_primary_key'
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/activerecord-3.1.1/lib/active_record/associations/collection_association.rb:51:in `ids_reader'
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/activerecord-3.1.1/lib/active_record/associations/builder/collection_association.rb:62:in `block in define_readers'
from (irb):12
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/railties-3.1.1/lib/rails/commands/console.rb:45:in `start'
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/railties-3.1.1/lib/rails/commands/console.rb:8:in `start'
from /Users/xxxxx/.rvm/gems/ruby-1.9.2-p320@rails-3.1.1/gems/railties-3.1.1/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
但是,获取实例会给出一个没有错误的列表:> widget.widget_spots
执行预期的 SQL 查询并给出一个列表。
我怎样才能弄清楚ActiveRecord::UnknownPrimaryKey
错误是在哪里以及如何产生的。它试图在哪个数据库中找到哪个主键?