Class: ActiveRecord::Associations::HasManyAssociation

Inherits:
AssociationCollection
  • Object
show all
Defined in:
lib/composite_primary_keys/associations.rb

Overview

:nodoc:

Direct Known Subclasses

HasManyThroughAssociation

Instance Method Summary collapse

Instance Method Details

#construct_sqlObject



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/composite_primary_keys/associations.rb', line 329

def construct_sql
  case
    when @reflection.options[:finder_sql]
      @finder_sql = interpolate_sql(@reflection.options[:finder_sql])

    when @reflection.options[:as]
      @finder_sql = 
        "#{@reflection.klass.quoted_table_name}.#{@reflection.options[:as]}_id = #{@owner.quoted_id} AND " + 
        "#{@reflection.klass.quoted_table_name}.#{@reflection.options[:as]}_type = #{@owner.class.quote_value(@owner.class.base_class.name.to_s)}"
      @finder_sql << " AND (#{conditions})" if conditions

    else
      @finder_sql = full_columns_equals(@reflection.klass.table_name, @reflection.primary_key_name, @owner.quoted_id)
      @finder_sql << " AND (#{conditions})" if conditions
  end

  if @reflection.options[:counter_sql]
    @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
  elsif @reflection.options[:finder_sql]
    # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
    @reflection.options[:counter_sql] = @reflection.options[:finder_sql].sub(/SELECT (\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
    @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
  else
    @counter_sql = @finder_sql
  end
end

#delete_records(records) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/composite_primary_keys/associations.rb', line 356

def delete_records(records)
  if @reflection.options[:dependent]
    records.each { |r| r.destroy }
  else
    connection = @reflection.active_record.connection
    field_names = @reflection.primary_key_name.split(',')
    field_names.collect! {|n| connection.quote_column_name(n) + " = NULL"}
    records.each do |r|
      where_clause = nil
      
      if r.quoted_id.to_s.include?(CompositePrimaryKeys::ID_SEP)
        where_clause_terms = [@reflection.klass.primary_key, r.quoted_id].transpose.map do |pair|
          "(#{connection.quote_column_name(pair[0])} = #{pair[1]})"
        end
        where_clause = where_clause_terms.join(" AND ")
      else
        where_clause = connection.quote_column_name(@reflection.klass.primary_key) + ' = ' +  r.quoted_id
      end
      
      @reflection.klass.update_all(  field_names.join(',') , where_clause)
    end
  end
end