Permalink
Browse files

Add an :autosave option for belongs_to associations.

  • Loading branch information...
1 parent 7a5b6a4 commit e6bd6d3008b14b2c9d91a20205871ebc0e5520b8 @laserlemon laserlemon committed Mar 7, 2011
View
2 lib/mongo_mapper/plugins/associations.rb
@@ -83,7 +83,7 @@ def save_to_collection(options={})
super if defined?(super)
associations.each do |association_name, association|
proxy = get_proxy(association)
- proxy.save_to_collection(options) if proxy.proxy_respond_to?(:save_to_collection)
+ proxy.save_to_collection(options) if proxy.proxy_respond_to?(:save_to_collection) && association.options[:autosave]
end
end
end
View
2 lib/mongo_mapper/plugins/associations/base.rb
@@ -6,7 +6,7 @@ class Base
attr_reader :name, :options, :query_options
# Options that should not be considered MongoDB query options/criteria
- AssociationOptions = [:as, :class, :class_name, :dependent, :extend, :foreign_key, :in, :polymorphic]
+ AssociationOptions = [:as, :class, :class_name, :dependent, :extend, :foreign_key, :in, :polymorphic, :autosave]
def initialize(name, options={}, &extension)
@name, @options, @query_options, @original_options = name, {}, {}, options
View
4 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
@@ -30,6 +30,10 @@ def create!(attrs={})
instantiate_target(:create!, attrs)
end
+ def save_to_collection(options={})
+ @target.save(options) if @target
+ end
+
protected
def find_target
return nil if proxy_owner[association.foreign_key].nil?
View
28 test/functional/associations/test_belongs_to_proxy.rb
@@ -181,4 +181,32 @@ class ::Thing
comment.post_id.should == post.id
end
end
+
+ context 'autosave' do
+ should 'not be true by default' do
+ @comment_class.associations[:post].options[:autosave].should_not be_true
+ end
+
+ should 'save parent changes when true' do
+ @comment_class.associations[:post].options[:autosave] = true
+
+ comment = @comment_class.create
+ post = comment.create_post(:title => 'Hello, world!')
+
+ comment.post.attributes = {:title => 'Hi, world.'}
+ comment.save
+
+ post.reload.title.should == 'Hi, world.'
+ end
+
+ should 'not save parent changes when false' do
+ comment = @comment_class.create
+ post = comment.create_post(:title => 'Hello, world!')
+
+ comment.post.attributes = {:title => 'Hi, world.'}
+ comment.save
+
+ post.reload.title.should == 'Hello, world!'
+ end
+ end
end

0 comments on commit e6bd6d3

Please sign in to comment.