blob: b9c9919e7a3c41f7b956e58a046e067bceec777e (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
module ActiveRecord
# = Active Record Has And Belongs To Many Association
module Associations
class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
attr_reader :join_table
def initialize(owner, reflection)
@join_table = Arel::Table.new(reflection.options[:join_table])
super
end
protected
def insert_record(record, validate = true)
return if record.new_record? && !record.save(:validate => validate)
if @reflection.options[:insert_sql]
@owner.connection.insert(interpolate(@reflection.options[:insert_sql], record))
else
stmt = join_table.compile_insert(
join_table[@reflection.foreign_key] => @owner.id,
join_table[@reflection.association_foreign_key] => record.id
)
@owner.connection.insert stmt.to_sql
end
record
end
def association_scope
super.joins(construct_joins)
end
private
def count_records
load_target.size
end
def delete_records(records, method)
if sql = @reflection.options[:delete_sql]
records.each { |record| @owner.connection.delete(interpolate(sql, record)) }
else
relation = join_table
stmt = relation.where(relation[@reflection.foreign_key].eq(@owner.id).
and(relation[@reflection.association_foreign_key].in(records.map { |x| x.id }.compact))
).compile_delete
@owner.connection.delete stmt.to_sql
end
end
def construct_joins
right = join_table
left = @reflection.klass.arel_table
condition = left[@reflection.klass.primary_key].eq(
right[@reflection.association_foreign_key])
right.create_join(right, right.create_on(condition))
end
def construct_owner_conditions
super(join_table)
end
def select_value
super || @reflection.klass.arel_table[Arel.star]
end
def invertible_for?(record)
false
end
end
end
end
|