Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add an :autosave option for belongs_to associations.

  • Loading branch information...
commit e6bd6d3008b14b2c9d91a20205871ebc0e5520b8 1 parent 7a5b6a4
Steve Richert laserlemon authored
2  lib/mongo_mapper/plugins/associations.rb
@@ -83,7 +83,7 @@ def save_to_collection(options={})
83 83 super if defined?(super)
84 84 associations.each do |association_name, association|
85 85 proxy = get_proxy(association)
86   - proxy.save_to_collection(options) if proxy.proxy_respond_to?(:save_to_collection)
  86 + proxy.save_to_collection(options) if proxy.proxy_respond_to?(:save_to_collection) && association.options[:autosave]
87 87 end
88 88 end
89 89 end
2  lib/mongo_mapper/plugins/associations/base.rb
@@ -6,7 +6,7 @@ class Base
6 6 attr_reader :name, :options, :query_options
7 7
8 8 # Options that should not be considered MongoDB query options/criteria
9   - AssociationOptions = [:as, :class, :class_name, :dependent, :extend, :foreign_key, :in, :polymorphic]
  9 + AssociationOptions = [:as, :class, :class_name, :dependent, :extend, :foreign_key, :in, :polymorphic, :autosave]
10 10
11 11 def initialize(name, options={}, &extension)
12 12 @name, @options, @query_options, @original_options = name, {}, {}, options
4 lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb
@@ -30,6 +30,10 @@ def create!(attrs={})
30 30 instantiate_target(:create!, attrs)
31 31 end
32 32
  33 + def save_to_collection(options={})
  34 + @target.save(options) if @target
  35 + end
  36 +
33 37 protected
34 38 def find_target
35 39 return nil if proxy_owner[association.foreign_key].nil?
28 test/functional/associations/test_belongs_to_proxy.rb
@@ -181,4 +181,32 @@ class ::Thing
181 181 comment.post_id.should == post.id
182 182 end
183 183 end
  184 +
  185 + context 'autosave' do
  186 + should 'not be true by default' do
  187 + @comment_class.associations[:post].options[:autosave].should_not be_true
  188 + end
  189 +
  190 + should 'save parent changes when true' do
  191 + @comment_class.associations[:post].options[:autosave] = true
  192 +
  193 + comment = @comment_class.create
  194 + post = comment.create_post(:title => 'Hello, world!')
  195 +
  196 + comment.post.attributes = {:title => 'Hi, world.'}
  197 + comment.save
  198 +
  199 + post.reload.title.should == 'Hi, world.'
  200 + end
  201 +
  202 + should 'not save parent changes when false' do
  203 + comment = @comment_class.create
  204 + post = comment.create_post(:title => 'Hello, world!')
  205 +
  206 + comment.post.attributes = {:title => 'Hi, world.'}
  207 + comment.save
  208 +
  209 + post.reload.title.should == 'Hello, world!'
  210 + end
  211 + end
184 212 end

0 comments on commit e6bd6d3

Please sign in to comment.
Something went wrong with that request. Please try again.