#634 stale
Brian Dainton

#create behaves like #create! on association proxies

Reported by Brian Dainton | July 16th, 2008 @ 06:30 PM | in 2.x

First, here's the branch of my Rails fork with the fix and tests exercising the (assumed correct) behavior for this issue.

In short, if you try to call #create on a HasAndBelongsToManyAssociation or HasManyThroughAssociation and pass in model attribute values that do not validate, the method no longer silently handles validation errors by producing an invalid AR instance and populating the object's 'errors'. Instead, it throws an ActiveRecord::RecordInvalid error (I expect this behavior from #create!, not #create).

Here are the updated tests which show the problem in action.

A validation added to the Person model:

class Person < ActiveRecord::Base
  has_many :posts, :through => :readers

  def validate 
    errors.add('first_name', 'is invalid') if read_attribute(:first_name) == 'InvalidName'
  end
end

Here are the updated tests for the HMT associations. The first test (a call to #create!) with an invalid :first_name properly raises the RecordInvalid error.

The second test (a call to #create) errors because it ALSO raises the RecordInvalid error.

class HasManyThroughAssociationsTest < ActiveRecord::TestCase
  fixtures :posts, :readers, :people

  def test_attempted_associate_with_invalid_create_exclamation_raises_error
    assert_raises(ActiveRecord::RecordInvalid) do
      posts(:thinking).people.create!(:first_name=>"InvalidName")
    end
  end
  
  def test_attempted_associate_with_invalid_create_does_not_raise_error
    person = posts(:thinking).people.create(:first_name=>"InvalidName")
    assert !person.valid?
    assert 1, person.errors.size
  end
end

Here are the updated tests for the HABTM associations. Likewise, the first test (a call to #create!) with an invalid :name properly raises the RecordInvalid error.

The second test (a call to #create) errors because it ALSO raises the RecordInvalid error.

class ProjectWithShortNamedDevelopers < ActiveRecord::Base
  set_table_name 'projects'
  has_and_belongs_to_many :developers,
    :class_name => "DeveloperWithShortName",
    :join_table => "developers_projects",
    :foreign_key => "project_id",
    :association_foreign_key => "developer_id"
end

class DeveloperWithShortName < ActiveRecord::Base
  set_table_name 'developers'
  has_and_belongs_to_many :projects,
    :class_name => "ProjectWithShortNamedDevelopers",
    :join_table => :developers_projects,
    :association_foreign_key => :project_id,
    :foreign_key => "developer_id"
    
  validates_length_of :name, :in => 3..10
end

class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
  def test_attempted_associate_with_invalid_create_exclamation_raises_error
    project = ProjectWithShortNamedDevelopers.find_by_name('Active Record')
    assert_raises(ActiveRecord::RecordInvalid) do
      project.developers.create!(:name => 'AnAbnormallyLongFirstName')
    end
  end
  
  def test_attempted_associate_with_invalid_create_does_not_raise_error
    project = ProjectWithShortNamedDevelopers.find_by_name('Active Record')
    developer = project.developers.create(:name => 'AnAbnormallyLongFirstName')
    assert !developer.valid?
    assert 1, developer.errors.size
  end
end

Tracking this down, it looks as if the #insert_record method on both of these associations is defaulting its 'force' param to true, when it should be false by default.

Comments and changes to this ticket

Please Login or create a free account to add a new comment.

You can update this ticket by sending an email to from your email client. (help)

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Source available from github

The Git repository resides at http://github.com/rails

Check out the current development trunk (Edge Rails) with:

git clone git://github.com/rails/rails.git

Creating or reviewing a patch

See the contributor guide.

Creating a feature request

Please don't. If you want a new feature in Rails, you'll have to pull up your sleeves and get busy yourself. Or convince someone else to do it. See the contributor guide on how to get going. But posting them here is just going to lead to ticket root.

Creating a bug report

When creating a bug report, be sure to include as much relevant information as possible. Post the code sample that causes the problem. Preferably, alter the unit tests and show through either changed or added tests how the expected behavior is not occuring.

Security vulnerabilities should be reported via an email to security@rubyonrails.org, do not use trac for reporting security vulnerabilities. All content in trac is publicly available as soon as it is posted.

Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kinda bug, you're creating this ticket in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the ticket automatically will see any activity or that others will jump to fix it. Creating a ticket like this is mostly to help yourself start on the path of fixing the problem and for others to sign on to with a "I'm having this problem too".

Shared Ticket Bins

People watching this ticket