Skip to content

Commit 3a66179

Browse files
chrisfinnerafaelfranca
authored andcommitted
AR .persisted? throws SystemStackError for an unsaved model with a
custom primary_key that didn't save due to validation error
1 parent eddcdb0 commit 3a66179

File tree

4 files changed

+16
-1
lines changed

4 files changed

+16
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
* Fixed error where .persisted? throws SystemStackError for an unsaved model with a
2+
custom primary key that didn't save due to validation error.
3+
4+
Fixes #14393.
5+
6+
*Chris Finne*
7+
18
* Introduce `validate` as an alias for `valid?`.
29

310
This is more intuitive when you want to run validations but don't care about the return value.

activerecord/lib/active_record/transactions.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ def restore_transaction_record_state(force = false) #:nodoc:
369369
@new_record = restore_state[:new_record]
370370
@destroyed = restore_state[:destroyed]
371371
if restore_state.has_key?(:id)
372-
self.id = restore_state[:id]
372+
write_attribute(self.class.primary_key, restore_state[:id])
373373
else
374374
@attributes.delete(self.class.primary_key)
375375
@attributes_cache.delete(self.class.primary_key)

activerecord/test/cases/transactions_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
require 'models/book'
66
require 'models/author'
77
require 'models/post'
8+
require 'models/movie'
89

910
class TransactionTest < ActiveRecord::TestCase
1011
self.use_transactional_fixtures = false
@@ -14,6 +15,11 @@ def setup
1415
@first, @second = Topic.find(1, 2).sort_by { |t| t.id }
1516
end
1617

18+
def test_persisted_in_a_model_with_custom_primary_key_after_failed_save
19+
movie = Movie.create
20+
assert !movie.persisted?
21+
end
22+
1723
def test_raise_after_destroy
1824
assert_not @first.frozen?
1925

activerecord/test/models/movie.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
class Movie < ActiveRecord::Base
22
self.primary_key = "movieid"
3+
4+
validates_presence_of :name
35
end

0 commit comments

Comments
 (0)