Skip to content
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

Raise error when generating attribute with dangerous name #47752

Merged
merged 1 commit into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions railties/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
* Raise error when generating attribute with dangerous name.

The following will now raise an error as `save` and `hash` are already
defined by Active Record.

```bash
bin/rails generate model Post save
bin/rails generate model Post hash
```

*Petrik de Heus*

## Rails 7.1.0.beta1 (September 13, 2023) ##

* Add ability to show slow tests to the test runner
Expand Down
8 changes: 8 additions & 0 deletions railties/lib/rails/generators/generated_attribute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ def parse(column_definition)
type, attr_options = *parse_type_and_options(type)
type = type.to_sym if type

if dangerous_name?(name)
raise Error, "Could not generate field '#{name}', as it is already defined by Active Record."
end

if type && !valid_type?(type)
raise Error, "Could not generate field '#{name}' with unknown type '#{type}'."
end
Expand All @@ -60,6 +64,10 @@ def parse(column_definition)
new(name, type, index_type, attr_options)
end

def dangerous_name?(name)
ActiveRecord::Base.dangerous_attribute_method?(name)
end

def valid_type?(type)
DEFAULT_TYPES.include?(type.to_s) ||
ActiveRecord::Base.connection.valid_type?(type)
Expand Down
8 changes: 8 additions & 0 deletions railties/test/generators/generated_attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ def teardown
Rails.application.config.active_record.belongs_to_required_by_default = @old_belongs_to_required_by_default
end

def test_field_name_with_dangerous_attribute_raises_error
e = assert_raise Rails::Generators::Error do
create_generated_attribute :string, :save
end
message = "Could not generate field 'save', as it is already defined by Active Record."
assert_match message, e.message
end

def test_field_type_returns_number_field
assert_field_type :integer, :number_field
end
Expand Down