我正在將項目升級到Rails 4.0.13(從3.2)。該項目有現有模型實體和聯繫人。我簡化了模型和數據庫結構以消除任何不相關的信息。ActiveRecord :: StaleObjectError在具有has_one關聯和accepted_nested_attributes_for的對象上 - 與gem'composite_primary_keys'衝突
的Gemfile:
source 'http://rubygems.org'
gem 'rails', '4.0.13'
gem 'mysql2', '~> 0.3.x'
gem 'composite_primary_keys'
遷移:
class CreateEntities < ActiveRecord::Migration
def change
create_table :entities do |t|
t.string :name
t.integer :lock_version
t.timestamps
end
end
end
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.integer :entity_id
t.integer :contact_type_id
t.string :name
t.integer :lock_version
t.timestamps
end
end
end
型號:
class Entity < ActiveRecord::Base
has_one :contact, -> { where contact_type_id: 1 }
accepts_nested_attributes_for :contact
end
class Contact < ActiveRecord::Base
belongs_to :entity
belongs_to :entity_contact_type
end
entities_test.rb:
require 'test_helper'
class EntityTest < ActiveSupport::TestCase
def test_auto_create_new_contact
entity = entities(:one)
entity.contact_attributes = { :name => 'new name' }
assert_difference 'Contact.count' do
entity.save
assert_equal 'new name', entity.contact.name
assert !entity.contact.new_record?
end
end
end
當我運行entities_test,我得到以下錯誤:
1) Error: EntityTest#test_auto_create_new_contact:
ActiveRecord::StaleObjectError: Attempted to update a stale object: Entity
test/unit/entity_test.rb:9:in `block in test_auto_create_new_contact' test/unit/entity_test.rb:8:in `test_auto_create_new_contact'
我創建了一個新的簡化的項目以隔離用於演示目的的問題,我已經收窄它下降到'composite_primary_keys'寶石。如果我從Gemfile中刪除該行,我不會收到錯誤。但是,在實踐中消除這種寶石不是一種選擇;項目的其他部分依賴於它。