[Feature Proposal] Add the associated record that blocks a save on ActiveRecord::RecordNotSaved

Pull request: Include record in ActiveRecord::RecordNotSaved by kassio · Pull Request #41513 · rails/rails · GitHub

Summary

Include the relation required to be saved in the ActiveRecord::RecordNotSaved exception raised when saving an association that requires the record to be saved.

Example:

class Post < ApplicationRecord
  has_many :comments

  validates :title, presence: true
end

class Comment < ApplicationRecord
  belongs_to :post
end
  • Before the fix
>> post = Post.new(title: :foo)
=> #<Post id: nil, title: "foo", body: nil, created_at: nil, updated_at: nil>
>> post.comments.create!
Traceback (most recent call last):
        1: from (irb):2
ActiveRecord::RecordNotSaved (You cannot call create unless the parent is saved)
>> e = _
=> #<ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved>
>> e.record
=> nil
  • After the fix
>> post = Post.new(title: :foo)
=> #<Post id: nil, title: "foo", body: nil, created_at: nil, updated_at: nil>
>> post.comments.create!
Traceback (most recent call last):
        1: from (irb):2
ActiveRecord::RecordNotSaved (You cannot call create unless the parent is saved)
>> e = _
=> #<ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved>
>> e.record
=> #<Post id: nil, title: "foo", body: nil, created_at: nil, updated_at: nil>

Other Information