nested_attributes.rb 15.6 KB
Newer Older
J
Jeremy Kemper 已提交
1 2 3
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/object/try'

4 5
module ActiveRecord
  module NestedAttributes #:nodoc:
6
    extend ActiveSupport::Concern
7 8 9 10

    included do
      class_inheritable_accessor :reject_new_nested_attributes_procs, :instance_writer => false
      self.reject_new_nested_attributes_procs = {}
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    end

    # == Nested Attributes
    #
    # 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:
    # <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:
    #
48
    #   params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
49
    #   member = Member.create(params)
50 51
    #   member.avatar.id # => 2
    #   member.avatar.icon # => 'smiling'
52 53 54
    #
    # It also allows you to update the avatar through the member:
    #
55
    #   params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
56
    #   member.update_attributes params['member']
57
    #   member.avatar.icon # => 'sad'
58 59 60 61 62 63 64 65 66 67 68
    #
    # 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
    #
69
    # Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
70 71
    # value that evaluates to +true+, you will destroy the associated model:
    #
72
    #   member.avatar_attributes = { :id => '2', :_destroy => '1' }
73 74 75 76 77 78 79 80 81 82 83 84
    #   member.avatar.marked_for_destruction? # => true
    #   member.save
    #   member.avatar #=> nil
    #
    # 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
85
    #     accepts_nested_attributes_for :posts
86 87 88 89 90
    #   end
    #
    # You can now set or update attributes on an associated post model through
    # the attribute hash.
    #
91
    # For each hash that does _not_ have an <tt>id</tt> key a new record will
92
    # be instantiated, unless the hash also contains a <tt>_destroy</tt> key
93 94 95 96 97 98
    # 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' },
99
    #       { :title => '', :_destroy => '1' } # this will be ignored
100
    #     ]
101 102 103
    #   }}
    #
    #   member = Member.create(params['member'])
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    #   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'
129
    #
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    #  Alternatively, :reject_if also accepts a symbol for using methods:
    #
    #    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)
    #        attributed['title].blank?
    #      end
    #    end
    #
146 147
    # If the hash contains an <tt>id</tt> key that matches an already
    # associated record, the matching record will be modified:
148 149
    #
    #   member.attributes = {
150 151 152 153 154
    #     :name => 'Joe',
    #     :posts_attributes => [
    #       { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
    #       { :id => 2, :title => '[UPDATED] other post' }
    #     ]
155 156
    #   }
    #
157 158
    #   member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
    #   member.posts.second.title # => '[UPDATED] other post'
159
    #
160 161 162
    # 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>
163
    # option. This will allow you to also use the <tt>_destroy</tt> key to
164
    # destroy existing records:
165 166 167 168 169 170
    #
    #   class Member < ActiveRecord::Base
    #     has_many :posts
    #     accepts_nested_attributes_for :posts, :allow_destroy => true
    #   end
    #
171
    #   params = { :member => {
172
    #     :posts_attributes => [{ :id => '2', :_destroy => '1' }]
173 174
    #   }}
    #
175 176 177 178 179 180 181 182 183 184 185 186 187
    #   member.attributes = params['member']
    #   member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
    #   member.posts.length #=> 2
    #   member.save
    #   member.posts.length # => 1
    #
    # === 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.
    module ClassMethods
188 189 190
      # 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.
191 192 193 194
      #
      # Supported options:
      # [:allow_destroy]
      #   If true, destroys any members from the attributes hash with a
195
      #   <tt>_destroy</tt> key and a value that evaluates to +true+
196 197
      #   (eg. 1, '1', true, or 'true'). This option is off by default.
      # [:reject_if]
198 199 200 201 202
      #   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
203
      #   do not have a <tt>_destroy</tt> value that evaluates to true.
204 205
      #   Passing <tt>:all_blank</tt> instead of a Proc will create a proc
      #   that will reject a record where all the attributes are blank.
206 207
      #
      # Examples:
208 209
      #   # creates avatar_attributes=
      #   accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
210 211
      #   # creates avatar_attributes=
      #   accepts_nested_attributes_for :avatar, :reject_if => :all_blank
212 213
      #   # creates avatar_attributes= and posts_attributes=
      #   accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      def accepts_nested_attributes_for(*attr_names)
        options = { :allow_destroy => false }
        options.update(attr_names.extract_options!)
        options.assert_valid_keys(:allow_destroy, :reject_if)

        attr_names.each do |association_name|
          if reflection = reflect_on_association(association_name)
            type = case reflection.macro
            when :has_one, :belongs_to
              :one_to_one
            when :has_many, :has_and_belongs_to_many
              :collection
            end

            reflection.options[:autosave] = true
229 230 231 232 233 234

            self.reject_new_nested_attributes_procs[association_name.to_sym] = if options[:reject_if] == :all_blank
              proc { |attributes| attributes.all? {|k,v| v.blank?} }
            else
              options[:reject_if]
            end
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250

            # def pirate_attributes=(attributes)
            #   assign_nested_attributes_for_one_to_one_association(:pirate, attributes, false)
            # end
            class_eval %{
              def #{association_name}_attributes=(attributes)
                assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes, #{options[:allow_destroy]})
              end
            }, __FILE__, __LINE__
          else
            raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
          end
        end
      end
    end

251 252 253
    # 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.
254 255
    #
    # See ActionView::Helpers::FormHelper::fields_for for more info.
256
    def _destroy
257 258 259
      marked_for_destruction?
    end

260 261 262 263 264 265 266
    # Deal with deprecated _delete.
    #
    def _delete #:nodoc:
      ActiveSupport::Deprecation.warn "_delete is deprecated in nested attributes. Use _destroy instead."
      _destroy
    end

267 268
    private

269 270
    # Attribute hash keys that should not be assigned as normal attributes.
    # These hash keys are nested attributes implementation details.
271 272 273 274
    #
    # TODO Remove _delete from UNASSIGNABLE_KEYS when deprecation warning are
    # removed.
    UNASSIGNABLE_KEYS = %w( id _destroy _delete )
275 276 277 278 279 280 281 282

    # Assigns the given attributes to the association.
    #
    # If the given attributes include an <tt>:id</tt> that matches the existing
    # record’s id, then the existing record will be modified. Otherwise a new
    # record will be built.
    #
    # If the given attributes include a matching <tt>:id</tt> attribute _and_ a
283
    # <tt>:_destroy</tt> key set to a truthy value, then the existing record
284
    # will be marked for destruction.
285
    def assign_nested_attributes_for_one_to_one_association(association_name, attributes, allow_destroy)
286 287 288 289
      attributes = attributes.stringify_keys

      if attributes['id'].blank?
        unless reject_new_record?(association_name, attributes)
290 291 292 293 294 295
          method = "build_#{association_name}"
          if respond_to?(method)
            send(method, attributes.except(*UNASSIGNABLE_KEYS))
          else
            raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
          end
296 297 298
        end
      elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s
        assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
299 300 301 302 303
      end
    end

    # Assigns the given attributes to the collection association.
    #
304 305 306
    # 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>
307
    # value and a <tt>:_destroy</tt> key set to a truthy value will mark the
308
    # matched record for destruction.
309 310 311 312
    #
    # For example:
    #
    #   assign_nested_attributes_for_collection_association(:people, {
313 314
    #     '1' => { :id => '1', :name => 'Peter' },
    #     '2' => { :name => 'John' },
315
    #     '3' => { :id => '2', :_destroy => true }
316 317
    #   })
    #
318
    # Will update the name of the Person with ID 1, build a new associated
P
Pratik Naik 已提交
319
    # person with the name `John', and mark the associated Person with ID 2
320 321 322 323 324 325 326
    # for destruction.
    #
    # Also accepts an Array of attribute hashes:
    #
    #   assign_nested_attributes_for_collection_association(:people, [
    #     { :id => '1', :name => 'Peter' },
    #     { :name => 'John' },
327
    #     { :id => '2', :_destroy => true }
328 329 330 331
    #   ])
    def assign_nested_attributes_for_collection_association(association_name, attributes_collection, allow_destroy)
      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})"
332 333
      end

334 335
      if attributes_collection.is_a? Hash
        attributes_collection = attributes_collection.sort_by { |index, _| index.to_i }.map { |_, attributes| attributes }
336 337
      end

338 339
      attributes_collection.each do |attributes|
        attributes = attributes.stringify_keys
340

341 342 343 344 345 346 347
        if attributes['id'].blank?
          unless reject_new_record?(association_name, attributes)
            send(association_name).build(attributes.except(*UNASSIGNABLE_KEYS))
          end
        elsif existing_record = send(association_name).detect { |record| record.id.to_s == attributes['id'].to_s }
          assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)
        end
348 349 350
      end
    end

351
    # Updates a record with the +attributes+ or marks it for destruction if
352
    # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
353
    def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
354
      if has_destroy_flag?(attributes) && allow_destroy
355 356
        record.mark_for_destruction
      else
357
        record.attributes = attributes.except(*UNASSIGNABLE_KEYS)
358 359
      end
    end
360

361 362 363 364
    # Determines if a hash contains a truthy _destroy key.
    def has_destroy_flag?(hash)
      ConnectionAdapters::Column.value_to_boolean(hash['_destroy']) ||
      ConnectionAdapters::Column.value_to_boolean(hash['_delete']) # TODO Remove after deprecation.
365 366 367
    end

    # Determines if a new record should be build by checking for
368
    # has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
369 370
    # association and evaluates to +true+.
    def reject_new_record?(association_name, attributes)
371 372 373 374 375 376 377 378 379 380 381 382
      has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
    end

    def call_reject_if(association_name, attributes)
      callback = self.class.reject_new_nested_attributes_procs[association_name]

      case callback
      when Symbol
        method(callback).arity == 0 ? send(callback) : send(callback, attributes)
      when Proc
        callback.try(:call, attributes)
      end
383
    end
384
  end
385
end