Skip to content

Commit

Permalink
Add an :autosave option for belongs_to associations.
Browse files Browse the repository at this point in the history
  • Loading branch information
laserlemon committed Mar 7, 2011
1 parent 7a5b6a4 commit e6bd6d3
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/mongo_mapper/plugins/associations.rb
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/mongo_mapper/plugins/associations/base.rb
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
Expand Up @@ -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?
Expand Down
28 changes: 28 additions & 0 deletions test/functional/associations/test_belongs_to_proxy.rb
Expand Up @@ -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.