0

假设我有模型

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错误是在哪里以及如何产生的。它试图在哪个数据库中找到哪个主键?

4

1 回答 1

0

这可能是因为目标widget_spots表的主键由多个字段组成。

于 2012-09-28T20:48:47.027 回答