diff options
Diffstat (limited to 'activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb')
-rw-r--r-- | activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb | 22 |
1 files changed, 10 insertions, 12 deletions
diff --git a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb index fd23e59e82..21a56fefd3 100644 --- a/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +++ b/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb @@ -23,7 +23,7 @@ module ActiveRecord options[:readonly] = finding_with_ambiguous_select?(options[:select] || @reflection.options[:select]) options[:select] ||= (@reflection.options[:select] || '*') end - + def count_records load_target.size end @@ -40,26 +40,23 @@ module ActiveRecord if @reflection.options[:insert_sql] @owner.connection.insert(interpolate_sql(@reflection.options[:insert_sql], record)) else + relation = arel_table(@reflection.options[:join_table]) attributes = columns.inject({}) do |attrs, column| case column.name.to_s when @reflection.primary_key_name.to_s - attrs[column.name] = owner_quoted_id + attrs[relation[column.name]] = owner_quoted_id when @reflection.association_foreign_key.to_s - attrs[column.name] = record.quoted_id + attrs[relation[column.name]] = record.quoted_id else if record.has_attribute?(column.name) value = @owner.send(:quote_value, record[column.name], column) - attrs[column.name] = value unless value.nil? + attrs[relation[column.name]] = value unless value.nil? end end attrs end - sql = - "INSERT INTO #{@owner.connection.quote_table_name @reflection.options[:join_table]} (#{@owner.send(:quoted_column_names, attributes).join(', ')}) " + - "VALUES (#{attributes.values.join(', ')})" - - @owner.connection.insert(sql) + relation.insert(attributes) end return true @@ -69,9 +66,10 @@ module ActiveRecord if sql = @reflection.options[:delete_sql] records.each { |record| @owner.connection.delete(interpolate_sql(sql, record)) } else - ids = quoted_record_ids(records) - sql = "DELETE FROM #{@owner.connection.quote_table_name @reflection.options[:join_table]} WHERE #{@reflection.primary_key_name} = #{owner_quoted_id} AND #{@reflection.association_foreign_key} IN (#{ids})" - @owner.connection.delete(sql) + relation = arel_table(@reflection.options[:join_table]) + relation.conditions(relation[@reflection.primary_key_name].eq(@owner.id). + and(Arel::In.new(relation[@reflection.association_foreign_key], records.map(&:id))) + ).delete end end |