Skip to content

Associations now raises ArgumentError on name conflicts. #13896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 31, 2014
Merged

Associations now raises ArgumentError on name conflicts. #13896

merged 1 commit into from
Jan 31, 2014

Conversation

laurocaetano
Copy link
Contributor

It's an attempt to fix #13217.

In order to avoid unexpected behavior, dangerous association names should raise ArgumentError.

This way, models like this:

class Project < ActiveRecord::Base
  has_many :errors
end
# It was deleting all the errors when saving, 
# because the valid? method calls errors.clear. 
# see https://github.com/rails/rails/blob/master/activemodel/lib/active_model/validations.rb#L312-L314

Will raise ArgumentError, saying that the association name will generate an instance method which is already defined by ActiveRecord::Base.

test 'dangerous association name raises ArgumentError' do
[:errors, 'errors', :save, 'save'].each do |name|
assert_raises(ArgumentError, "Association #{name} should not be allowed") do
Post.belongs_to name

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

has_one?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks :)
copy/paste :trollface:

@laurocaetano
Copy link
Contributor Author

@carlosantoniodasilva @chancancode updated with the suggested changes. Thanks guys :)

Dangerous association names conflicts include instance or class
methods already defined by `ActiveRecord::Base`.
carlosantoniodasilva added a commit that referenced this pull request Jan 31, 2014
Associations now raises `ArgumentError` on name conflicts. Closes #13217.
@carlosantoniodasilva carlosantoniodasilva merged commit 5df5296 into rails:master Jan 31, 2014
@carlosantoniodasilva
Copy link
Member

Thanks!

@laurocaetano
Copy link
Contributor Author

Thanks 💚

@laurocaetano laurocaetano deleted the dangerous_association_names branch May 6, 2020 09:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

has_many :dependent => :destroy deleting associations on update_attributes
3 participants