我一直在调试Rails的这个奇怪问题,即使我的表ID在那儿也给我“表的未知主键...”。
我已将数据库从一个heroku应用程序复制到另一个,在原始数据库上没有问题,新的数据库出现了数据库错误。
这是错误:
ProductsController# (ActionView::Template::Error) "Unknown primary key for table collections in model Collection."
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:366:in `primary_key'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:480:in `association_primary_key'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:58:in `block in add_constraints'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `each_with_index'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `add_constraints'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:31:in `scope'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:98:in `association_scope'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:87:in `scoped'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:573:in `first_or_last'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:105:in `last'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_proxy.rb:46:in `last'
/app/app/helpers/likes_helper.rb:62:in `significant_liker'
导致它的行:
product.collections.last.try :user
和表:
d8apjspa441pad=> \d collections
Table "public.collections"
Column | Type | Modifiers
----------------+------------------------+----------------------------------------------------------
id | integer | not null default nextval('collections_id_seq'::regclass)
name | character varying(255) |
user_id | integer |
permalink | character varying(255) |
category_id | integer |
products_count | integer |
is_featured | boolean |
Indexes:
"index_lists_on_user_id_and_permalink" UNIQUE, btree (user_id, permalink)
知道为什么会发生这种情况吗?
谢谢!
似乎表集合缺少主键。
在Rails 3.2之前,在模型中设置主键,例如
class Collection < ActiveRecord::Base
set_primary_key "my_existing_column"
end
在Rails 3.2+和Rails 4中,在模型中设置主键,例如
class Collection < ActiveRecord::Base
self.primary_key = "my_existing_column"
end
或者
我们可以更改表并为id设置主键,例如
创建一个迁移文件以设置主键
class AddPrimaryKeyToCollections < ActiveRecord::Migration
def change
execute "ALTER TABLE collections ADD PRIMARY KEY (id);"
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句