From 06075a9eb5ddf255ed561bc4cdddef214d7c63aa Mon Sep 17 00:00:00 2001 From: Rick Olson Date: Mon, 29 May 2006 03:48:17 +0000 Subject: Fix the has_and_belongs_to_many #create doesn't populate the join for new records. Closes #3692 [josh@hasmanythrough.com] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4379 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/lib/active_record/associations.rb | 6 ++++++ .../associations/has_and_belongs_to_many_association.rb | 11 +++++++++++ 2 files changed, 17 insertions(+) (limited to 'activerecord/lib') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index e1a0289039..ff10763cbf 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -763,6 +763,10 @@ module ActiveRecord # * collection.size - returns the number of associated objects. # * collection.find(id) - finds an associated object responding to the +id+ and that # meets the condition that it has to be associated with this object. + # * collection.build(attributes = {}) - returns a new object of the collection type that has been instantiated + # with +attributes+ and linked to this object through the join table but has not yet been saved. + # * collection.create(attributes = {}) - returns a new object of the collection type that has been instantiated + # with +attributes+ and linked to this object through the join table and that has already been saved (if it passed the validation). # # Example: An Developer class declares has_and_belongs_to_many :projects, which will add: # * Developer#projects @@ -775,6 +779,8 @@ module ActiveRecord # * Developer#projects.empty? # * Developer#projects.size # * Developer#projects.find(id) + # * Developer#projects.build (similar to Project.new("project_id" => id)) + # * Developer#projects.create (similar to c = Project.new("project_id" => id); c.save; c) # The declaration may include an options hash to specialize the behavior of the association. # # Options are: 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 cc6549f3ae..42cf549dcb 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 @@ -13,6 +13,17 @@ module ActiveRecord record end + def create(attributes = {}) + # Can't use Base.create since the foreign key may be a protected attribute. + if attributes.is_a?(Array) + attributes.collect { |attr| create(attr) } + else + record = build(attributes) + insert_record(record) unless @owner.new_record? + record + end + end + def find_first load_target.first end -- cgit v1.2.3