aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb
diff options
context:
space:
mode:
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.rb37
1 files changed, 16 insertions, 21 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 d67207fa4d..13c99455c0 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
@@ -8,33 +8,15 @@ module ActiveRecord
def build(attributes = {})
load_target
- record = @reflection.klass.new(attributes)
- @target << record
- record
+ build_record(attributes)
end
def create(attributes = {})
- # Can't use Base.create because the foreign key may be a protected attribute.
- ensure_owner_is_not_new
- if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr) }
- else
- record = build(attributes)
- insert_record(record) unless @owner.new_record?
- record
- end
+ create_record(attributes) { |record| insert_record(record) }
end
def create!(attributes = {})
- # Can't use Base.create! because the foreign key may be a protected attribute.
- ensure_owner_is_not_new
- if attributes.is_a?(Array)
- attributes.collect { |attr| create(attr) }
- else
- record = build(attributes)
- insert_record(record, true) unless @owner.new_record?
- record
- end
+ create_record(attributes) { |record| insert_record(record, true) }
end
def find_first
@@ -160,6 +142,19 @@ module ActiveRecord
def finding_with_ambiguous_select?(select_clause)
!select_clause && @owner.connection.columns(@reflection.options[:join_table], "Join Table Columns").size != 2
end
+
+ private
+ def create_record(attributes)
+ # Can't use Base.create because the foreign key may be a protected attribute.
+ ensure_owner_is_not_new
+ if attributes.is_a?(Array)
+ attributes.collect { |attr| create(attr) }
+ else
+ record = build(attributes)
+ yield(record)
+ record
+ end
+ end
end
end
end