假设我有模特
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
错误的位置和方式。它试图在哪个数据库中找到哪个主键?
答案 0 :(得分:0)
这可能会发生,因为目标widget_spots
表的主键由多个字段组成。