88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
|
# File 'lib/activerecord-import/import.rb', line 88
def import(*args, &block)
unless owner.persisted?
raise ActiveRecord::RecordNotSaved, "You cannot call import unless the parent is saved"
end
options = args.last.is_a?(Hash) ? args.pop : {}
model_klass = reflection.klass
symbolized_foreign_key = reflection.foreign_key.to_sym
symbolized_column_names = model_klass.column_names.map(&:to_sym)
owner_primary_key = owner.class.primary_key
owner_primary_key_value = owner.send(owner_primary_key)
if args.last.is_a?( Array ) && args.last.first.is_a?(ActiveRecord::Base)
if args.length == 2
models = args.last
column_names = args.first
else
models = args.first
column_names = symbolized_column_names
end
unless symbolized_column_names.include?(symbolized_foreign_key)
column_names << symbolized_foreign_key
end
models.each do |m|
m.public_send "#{symbolized_foreign_key}=", owner_primary_key_value
m.public_send "#{reflection.type}=", owner.class.name if reflection.type
end
return model_klass.import column_names, models, options
elsif args.last.is_a?( Array ) && args.last.empty?
return ActiveRecord::Import::Result.new([], 0, [])
elsif args.size == 2 && args.first.is_a?( Array ) && args.last.is_a?( Array )
column_names, array_of_attributes = args
symbolized_column_names = column_names.map(&:to_s)
if symbolized_column_names.include?(symbolized_foreign_key)
index = symbolized_column_names.index(symbolized_foreign_key)
array_of_attributes.each { |attrs| attrs[index] = owner_primary_key_value }
else
column_names << symbolized_foreign_key
array_of_attributes.each { |attrs| attrs << owner_primary_key_value }
end
if reflection.type
column_names << reflection.type
array_of_attributes.each { |attrs| attrs << owner.class.name }
end
return model_klass.import column_names, array_of_attributes, options
else
raise ArgumentError, "Invalid arguments!"
end
end
|