Ensure that 'autosaving' works when associations aren't loaded [Bryan Helmkamp] References #8713
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7824 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
parent
4db4661a67
commit
1c881ca5bf
|
@ -1072,12 +1072,15 @@ module ActiveRecord
|
|||
after_callback = <<-end_eval
|
||||
association = instance_variable_get("@#{association_name}")
|
||||
|
||||
if association.respond_to?(:loaded?) && association.loaded?
|
||||
if @new_record_before_save
|
||||
records_to_save = association
|
||||
records_to_save = if @new_record_before_save
|
||||
association
|
||||
elsif association.respond_to?(:loaded?) && association.loaded?
|
||||
association.select { |record| record.new_record? }
|
||||
else
|
||||
records_to_save = association.select { |record| record.new_record? }
|
||||
[]
|
||||
end
|
||||
|
||||
if !records_to_save.blank?
|
||||
records_to_save.each { |record| association.send(:insert_record, record) }
|
||||
association.send(:construct_sql) # reconstruct the SQL queries now that we know the owner's id
|
||||
end
|
||||
|
|
|
@ -101,6 +101,10 @@ class AssociationProxyTest < Test::Unit::TestCase
|
|||
assert !david.projects.loaded?
|
||||
end
|
||||
|
||||
def test_save_on_parent_saves_children
|
||||
developer = Developer.create :name => "Bryan", :salary => 50_000
|
||||
assert_equal 1, developer.reload.audit_logs.size
|
||||
end
|
||||
end
|
||||
|
||||
class HasOneAssociationsTest < Test::Unit::TestCase
|
||||
|
|
|
@ -75,4 +75,9 @@ ActiveRecord::Schema.define do
|
|||
t.column :real_number, :real
|
||||
end
|
||||
end
|
||||
|
||||
create_table :audit_logs, :force => true do |t|
|
||||
t.column :message, :string, :null=>false
|
||||
t.column :developer_id, :integer, :null=>false
|
||||
end
|
||||
end
|
||||
|
|
|
@ -41,8 +41,18 @@ class Developer < ActiveRecord::Base
|
|||
|
||||
has_and_belongs_to_many :special_projects, :join_table => 'developers_projects', :association_foreign_key => 'project_id'
|
||||
|
||||
has_many :audit_logs
|
||||
|
||||
validates_inclusion_of :salary, :in => 50000..200000
|
||||
validates_length_of :name, :within => 3..20
|
||||
|
||||
before_create do |developer|
|
||||
developer.audit_logs.build :message => "Computer created"
|
||||
end
|
||||
end
|
||||
|
||||
class AuditLog < ActiveRecord::Base
|
||||
belongs_to :developer
|
||||
end
|
||||
|
||||
DeveloperSalary = Struct.new(:amount)
|
||||
|
|
Loading…
Reference in New Issue