我有 A 型和 B 型;A has_many B, and B belongs_to A. 到目前为止,一切都很好——除了,我指定 B 没有主键。我不打算修改或删除单独的 B 行,我希望有几百万到十亿个,所以省略主键将非常方便,空间方面。
创建 B 表的迁移如下所示:
class CreateBs < ActiveRecord::Migration
def change
create_table :bs, {:id => false} do |t|
# … rest of fields …
end
end
end
不幸的是,ActiveRecord 不同意。尝试创建 A(没错!)会导致:
1.9.3p194 :001 > A.create!
(0.3ms) BEGIN
(0.1ms) ROLLBACK
ActiveRecord::UnknownPrimaryKey: ActiveRecord::UnknownPrimaryKey
from /Users/annelicuss/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/reflection.rb:366:in `primary_key'
from /Users/annelicuss/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/reflection.rb:216:in `association_primary_key'
from /Users/annelicuss/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/associations/has_many_association.rb:104:in `foreign_key_present?'
from /Users/annelicuss/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/associations/association.rb:165:in `find_target?'
from /Users/annelicuss/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/associations/collection_association.rb:332:in `load_target'
from /Users/annelicuss/.rvm/gems/ruby-1.9.3-p194/gems/activerecord-3.2.8/lib/active_record/associations/collection_proxy.rb:44:in `load_target'
…
如果你捕捉到异常,它的message
状态:
"Unknown primary key for table bs in model B."
(这是因为 B 没有主键。)
我不想有这个问题!有什么办法吗?