Class: RailsCoreExtensions::TransferRecords

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_core_extensions/transfer_records.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent, klass, options = {}) ⇒ TransferRecords

Returns a new instance of TransferRecords.



3
4
5
6
7
# File 'lib/rails_core_extensions/transfer_records.rb', line 3

def initialize(parent, klass, options = {})
  @parent = parent
  @klass = klass
  @options = options
end

Instance Method Details

#transfer_from(objects) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/rails_core_extensions/transfer_records.rb', line 9

def transfer_from(objects)
  record_ids = objects.flat_map { |o|
    o.send(@klass.name.underscore + '_ids')
  }
  unless record_ids.empty?
    @options[:foreign_key] ||= @parent.class.name.underscore + '_id'
    update_options = @options.except(:foreign_key)
    update_options[@options[:foreign_key]] = @parent.id
    @klass.where(id: record_ids).update_all(update_options)
  end
end