nested_attributes.rb 19.9 KB
Newer Older
J
Jeremy Kemper 已提交
1 2
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/try'
3
require 'active_support/core_ext/object/blank'
4
require 'active_support/core_ext/hash/indifferent_access'
5
require 'active_support/core_ext/class/attribute'
J
Jeremy Kemper 已提交
6

7 8
module ActiveRecord
  module NestedAttributes #:nodoc:
9 10 11
    class TooManyRecords < ActiveRecordError
    end

12
    extend ActiveSupport::Concern
13 14

    included do
15
      config_attribute :nested_attributes_options
16
      self.nested_attributes_options = {}
17 18
    end

R
Rizwan Reza 已提交
19
    # = Active Record Nested Attributes
20 21 22 23 24 25 26 27 28
    #
    # Nested attributes allow you to save attributes on associated records
    # through the parent. By default nested attribute updating is turned off,
    # you can enable it using the accepts_nested_attributes_for class method.
    # When you enable nested attributes an attribute writer is defined on
    # the model.
    #
    # The attribute writer is named after the association, which means that
    # in the following example, two new methods are added to your model:
29
    #
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    # <tt>author_attributes=(attributes)</tt> and
    # <tt>pages_attributes=(attributes)</tt>.
    #
    #   class Book < ActiveRecord::Base
    #     has_one :author
    #     has_many :pages
    #
    #     accepts_nested_attributes_for :author, :pages
    #   end
    #
    # Note that the <tt>:autosave</tt> option is automatically enabled on every
    # association that accepts_nested_attributes_for is used for.
    #
    # === One-to-one
    #
    # Consider a Member model that has one Avatar:
    #
    #   class Member < ActiveRecord::Base
    #     has_one :avatar
    #     accepts_nested_attributes_for :avatar
    #   end
    #
    # Enabling nested attributes on a one-to-one association allows you to
    # create the member and avatar in one go:
    #
55
    #   params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
P
Pratik Naik 已提交
56
    #   member = Member.create(params[:member])
57 58
    #   member.avatar.id # => 2
    #   member.avatar.icon # => 'smiling'
59 60 61
    #
    # It also allows you to update the avatar through the member:
    #
P
Pratik Naik 已提交
62 63
    #   params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
    #   member.update_attributes params[:member]
64
    #   member.avatar.icon # => 'sad'
65 66 67 68 69 70 71 72 73 74 75
    #
    # By default you will only be able to set and update attributes on the
    # associated model. If you want to destroy the associated model through the
    # attributes hash, you have to enable it first using the
    # <tt>:allow_destroy</tt> option.
    #
    #   class Member < ActiveRecord::Base
    #     has_one :avatar
    #     accepts_nested_attributes_for :avatar, :allow_destroy => true
    #   end
    #
76
    # Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
77 78
    # value that evaluates to +true+, you will destroy the associated model:
    #
79
    #   member.avatar_attributes = { :id => '2', :_destroy => '1' }
80 81
    #   member.avatar.marked_for_destruction? # => true
    #   member.save
82
    #   member.reload.avatar # => nil
83 84 85 86 87 88 89 90 91
    #
    # Note that the model will _not_ be destroyed until the parent is saved.
    #
    # === One-to-many
    #
    # Consider a member that has a number of posts:
    #
    #   class Member < ActiveRecord::Base
    #     has_many :posts
92
    #     accepts_nested_attributes_for :posts
93 94 95 96 97
    #   end
    #
    # You can now set or update attributes on an associated post model through
    # the attribute hash.
    #
98
    # For each hash that does _not_ have an <tt>id</tt> key a new record will
99
    # be instantiated, unless the hash also contains a <tt>_destroy</tt> key
100 101 102 103 104 105
    # that evaluates to +true+.
    #
    #   params = { :member => {
    #     :name => 'joe', :posts_attributes => [
    #       { :title => 'Kari, the awesome Ruby documentation browser!' },
    #       { :title => 'The egalitarian assumption of the modern citizen' },
106
    #       { :title => '', :_destroy => '1' } # this will be ignored
107
    #     ]
108 109 110
    #   }}
    #
    #   member = Member.create(params['member'])
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    #   member.posts.length # => 2
    #   member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
    #   member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
    #
    # You may also set a :reject_if proc to silently ignore any new record
    # hashes if they fail to pass your criteria. For example, the previous
    # example could be rewritten as:
    #
    #    class Member < ActiveRecord::Base
    #      has_many :posts
    #      accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
    #    end
    #
    #   params = { :member => {
    #     :name => 'joe', :posts_attributes => [
    #       { :title => 'Kari, the awesome Ruby documentation browser!' },
    #       { :title => 'The egalitarian assumption of the modern citizen' },
    #       { :title => '' } # this will be ignored because of the :reject_if proc
    #     ]
    #   }}
    #
    #   member = Member.create(params['member'])
    #   member.posts.length # => 2
    #   member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
    #   member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
136
    #
137
    # Alternatively, :reject_if also accepts a symbol for using methods:
138 139 140 141 142 143 144 145 146 147 148
    #
    #    class Member < ActiveRecord::Base
    #      has_many :posts
    #      accepts_nested_attributes_for :posts, :reject_if => :new_record?
    #    end
    #
    #    class Member < ActiveRecord::Base
    #      has_many :posts
    #      accepts_nested_attributes_for :posts, :reject_if => :reject_posts
    #
    #      def reject_posts(attributed)
149
    #        attributed['title'].blank?
150 151 152
    #      end
    #    end
    #
153 154
    # If the hash contains an <tt>id</tt> key that matches an already
    # associated record, the matching record will be modified:
155 156
    #
    #   member.attributes = {
157 158 159 160 161
    #     :name => 'Joe',
    #     :posts_attributes => [
    #       { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
    #       { :id => 2, :title => '[UPDATED] other post' }
    #     ]
162 163
    #   }
    #
164 165
    #   member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
    #   member.posts.second.title # => '[UPDATED] other post'
166
    #
167 168 169
    # By default the associated records are protected from being destroyed. If
    # you want to destroy any of the associated records through the attributes
    # hash, you have to enable it first using the <tt>:allow_destroy</tt>
170
    # option. This will allow you to also use the <tt>_destroy</tt> key to
171
    # destroy existing records:
172 173 174 175 176 177
    #
    #   class Member < ActiveRecord::Base
    #     has_many :posts
    #     accepts_nested_attributes_for :posts, :allow_destroy => true
    #   end
    #
178
    #   params = { :member => {
179
    #     :posts_attributes => [{ :id => '2', :_destroy => '1' }]
180 181
    #   }}
    #
182 183
    #   member.attributes = params['member']
    #   member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
184
    #   member.posts.length # => 2
185
    #   member.save
P
Pratik Naik 已提交
186
    #   member.reload.posts.length # => 1
187 188 189 190 191 192 193
    #
    # === Saving
    #
    # All changes to models, including the destruction of those marked for
    # destruction, are saved and destroyed automatically and atomically when
    # the parent model is saved. This happens inside the transaction initiated
    # by the parents save method. See ActiveRecord::AutosaveAssociation.
194 195 196 197 198 199 200 201 202 203 204 205
    #
    # === Using with attr_accessible
    #
    # The use of <tt>attr_accessible</tt> can interfere with nested attributes
    # if you're not careful. For example, if the <tt>Member</tt> model above
    # was using <tt>attr_accessible</tt> like this:
    #
    #   attr_accessible :name
    #
    # You would need to modify it to look like this:
    #
    #   attr_accessible :name, :posts_attributes
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    #
    # === Validating the presence of a parent model
    #
    # If you want to validate that a child record is associated with a parent
    # record, you can use <tt>validates_presence_of</tt> and
    # <tt>inverse_of</tt> as this example illustrates:
    #
    #   class Member < ActiveRecord::Base
    #     has_many :posts, :inverse_of => :member
    #     accepts_nested_attributes_for :posts
    #   end
    #
    #   class Post < ActiveRecord::Base
    #     belongs_to :member, :inverse_of => :posts
    #     validates_presence_of :member
    #   end
222
    module ClassMethods
223
      REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
224

225 226 227
      # Defines an attributes writer for the specified association(s). If you
      # are using <tt>attr_protected</tt> or <tt>attr_accessible</tt>, then you
      # will need to add the attribute writer to the allowed list.
228 229 230 231
      #
      # Supported options:
      # [:allow_destroy]
      #   If true, destroys any members from the attributes hash with a
232
      #   <tt>_destroy</tt> key and a value that evaluates to +true+
233 234
      #   (eg. 1, '1', true, or 'true'). This option is off by default.
      # [:reject_if]
235 236 237 238 239
      #   Allows you to specify a Proc or a Symbol pointing to a method
      #   that checks whether a record should be built for a certain attribute
      #   hash. The hash is passed to the supplied Proc or the method
      #   and it should return either +true+ or +false+. When no :reject_if
      #   is specified, a record will be built for all attribute hashes that
240
      #   do not have a <tt>_destroy</tt> value that evaluates to true.
241
      #   Passing <tt>:all_blank</tt> instead of a Proc will create a proc
242 243
      #   that will reject a record where all the attributes are blank excluding
      #   any value for _destroy.
244 245
      # [:limit]
      #   Allows you to specify the maximum number of the associated records that
A
Adam Meehan 已提交
246
      #   can be processed with the nested attributes. If the size of the
247 248 249
      #   nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
      #   exception is raised. If omitted, any number associations can be processed.
      #   Note that the :limit option is only applicable to one-to-many associations.
250
      # [:update_only]
251 252 253
      #   Allows you to specify that an existing record may only be updated.
      #   A new record may only be created when there is no existing record.
      #   This option only works for one-to-one associations and is ignored for
254
      #   collection associations. This option is off by default.
255 256
      #
      # Examples:
257 258
      #   # creates avatar_attributes=
      #   accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
259 260
      #   # creates avatar_attributes=
      #   accepts_nested_attributes_for :avatar, :reject_if => :all_blank
261 262
      #   # creates avatar_attributes= and posts_attributes=
      #   accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
263
      def accepts_nested_attributes_for(*attr_names)
264
        options = { :allow_destroy => false, :update_only => false }
265
        options.update(attr_names.extract_options!)
266
        options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
267
        options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
268 269 270 271

        attr_names.each do |association_name|
          if reflection = reflect_on_association(association_name)
            reflection.options[:autosave] = true
272
            add_autosave_association_callbacks(reflection)
273 274

            nested_attributes_options = self.nested_attributes_options.dup
275
            nested_attributes_options[association_name.to_sym] = options
276 277
            self.nested_attributes_options = nested_attributes_options

278
            type = (reflection.collection? ? :collection : :one_to_one)
279

280 281
            # def pirate_attributes=(attributes)
            #   assign_nested_attributes_for_one_to_one_association(:pirate, attributes, mass_assignment_options)
282
            # end
283
            class_eval <<-eoruby, __FILE__, __LINE__ + 1
284 285 286
              if method_defined?(:#{association_name}_attributes=)
                remove_method(:#{association_name}_attributes=)
              end
287 288
              def #{association_name}_attributes=(attributes)
                assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, mass_assignment_options)
289
              end
290
            eoruby
291 292 293 294 295 296 297
          else
            raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
          end
        end
      end
    end

298 299 300
    # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
    # used in conjunction with fields_for to build a form element for the
    # destruction of this association.
301 302
    #
    # See ActionView::Helpers::FormHelper::fields_for for more info.
303
    def _destroy
304 305 306 307 308
      marked_for_destruction?
    end

    private

309 310
    # Attribute hash keys that should not be assigned as normal attributes.
    # These hash keys are nested attributes implementation details.
311
    UNASSIGNABLE_KEYS = %w( id _destroy )
312 313 314

    # Assigns the given attributes to the association.
    #
315
    # If update_only is false and the given attributes include an <tt>:id</tt>
316
    # that matches the existing record's id, then the existing record will be
317 318
    # modified. If update_only is true, a new record is only created when no
    # object exists. Otherwise a new record will be built.
319
    #
320 321 322
    # If the given attributes include a matching <tt>:id</tt> attribute, or
    # update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
    # then the existing record will be marked for destruction.
323
    def assign_nested_attributes_for_one_to_one_association(association_name, attributes, assignment_opts = {})
324
      options = self.nested_attributes_options[association_name]
325
      attributes = attributes.with_indifferent_access
326

327
      if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
328
          (options[:update_only] || record.id.to_s == attributes['id'].to_s)
329
        assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy], assignment_opts) unless call_reject_if(association_name, attributes)
330

331
      elsif attributes['id'].present? && !assignment_opts[:without_protection]
332
        raise_nested_attributes_record_not_found(association_name, attributes['id'])
333

334 335 336
      elsif !reject_new_record?(association_name, attributes)
        method = "build_#{association_name}"
        if respond_to?(method)
337
          send(method, attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
338
        else
339
          raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
340
        end
341 342 343 344 345
      end
    end

    # Assigns the given attributes to the collection association.
    #
346 347 348
    # Hashes with an <tt>:id</tt> value matching an existing associated record
    # will update that record. Hashes without an <tt>:id</tt> value will build
    # a new record for the association. Hashes with a matching <tt>:id</tt>
349
    # value and a <tt>:_destroy</tt> key set to a truthy value will mark the
350
    # matched record for destruction.
351 352 353 354
    #
    # For example:
    #
    #   assign_nested_attributes_for_collection_association(:people, {
355 356
    #     '1' => { :id => '1', :name => 'Peter' },
    #     '2' => { :name => 'John' },
357
    #     '3' => { :id => '2', :_destroy => true }
358 359
    #   })
    #
360
    # Will update the name of the Person with ID 1, build a new associated
P
Pratik Naik 已提交
361
    # person with the name `John', and mark the associated Person with ID 2
362 363 364 365 366 367 368
    # for destruction.
    #
    # Also accepts an Array of attribute hashes:
    #
    #   assign_nested_attributes_for_collection_association(:people, [
    #     { :id => '1', :name => 'Peter' },
    #     { :name => 'John' },
369
    #     { :id => '2', :_destroy => true }
370
    #   ])
371
    def assign_nested_attributes_for_collection_association(association_name, attributes_collection, assignment_opts = {})
372
      options = self.nested_attributes_options[association_name]
373

374 375
      unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
        raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
376 377
      end

378 379 380 381
      if options[:limit] && attributes_collection.size > options[:limit]
        raise TooManyRecords, "Maximum #{options[:limit]} records are allowed. Got #{attributes_collection.size} records instead."
      end

382
      if attributes_collection.is_a? Hash
383 384
        keys = attributes_collection.keys
        attributes_collection = if keys.include?('id') || keys.include?(:id)
385
          [attributes_collection]
386
        else
A
Aaron Patterson 已提交
387
          attributes_collection.values
388
        end
389 390
      end

391
      association = association(association_name)
392 393

      existing_records = if association.loaded?
394
        association.target
395 396
      else
        attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
397
        attribute_ids.empty? ? [] : association.scoped.where(association.klass.primary_key => attribute_ids)
398 399
      end

400
      attributes_collection.each do |attributes|
401
        attributes = attributes.with_indifferent_access
402

403 404
        if attributes['id'].blank?
          unless reject_new_record?(association_name, attributes)
405
            association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
406
          end
407
        elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
408 409 410
          unless association.loaded? || call_reject_if(association_name, attributes)
            # Make sure we are operating on the actual object which is in the association's
            # proxy_target array (either by finding it, or adding it if not found)
411
            target_record = association.target.detect { |record| record == existing_record }
412 413 414 415

            if target_record
              existing_record = target_record
            else
416
              association.add_to_target(existing_record)
417 418
            end

419
          end
420

421
          if !call_reject_if(association_name, attributes)
422
            assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy], assignment_opts)
423
          end
424 425
        elsif assignment_opts[:without_protection]
          association.build(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
426 427
        else
          raise_nested_attributes_record_not_found(association_name, attributes['id'])
428
        end
429 430 431
      end
    end

432
    # Updates a record with the +attributes+ or marks it for destruction if
433
    # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
434 435
    def assign_to_or_mark_for_destruction(record, attributes, allow_destroy, assignment_opts)
      record.assign_attributes(attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
436
      record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
437
    end
438

439 440
    # Determines if a hash contains a truthy _destroy key.
    def has_destroy_flag?(hash)
441
      ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
442 443
    end

444
    # Determines if a new record should be build by checking for
445
    # has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
446 447
    # association and evaluates to +true+.
    def reject_new_record?(association_name, attributes)
448 449 450 451
      has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
    end

    def call_reject_if(association_name, attributes)
452
      return false if has_destroy_flag?(attributes)
453
      case callback = self.nested_attributes_options[association_name][:reject_if]
454 455 456
      when Symbol
        method(callback).arity == 0 ? send(callback) : send(callback, attributes)
      when Proc
457
        callback.call(attributes)
458
      end
459
    end
460

461
    def raise_nested_attributes_record_not_found(association_name, record_id)
E
Emilio Tagua 已提交
462
      raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
463
    end
464 465 466 467

    def unassignable_keys(assignment_opts)
      assignment_opts[:without_protection] ? UNASSIGNABLE_KEYS - %w[id] : UNASSIGNABLE_KEYS
    end
468
  end
469
end