diff --git a/CHANGELOG.md b/CHANGELOG.md index 119bc9bb12..7dd73a7561 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Bug fixes +* [#509](https://github.com/rubocop/rubocop-rails/pull/509): Fix an error for `Rails/ReflectionClassName` when using `class_name: to_s`. ([@skryukov][]) * [#507](https://github.com/rubocop/rubocop-rails/pull/507): Fix an error for `Rails/FindBy` when calling `take` after block. ([@koic][]) * [#504](https://github.com/rubocop/rubocop-rails/issues/504): Fix a false positive for `Rails/FindBy` when receiver is not an Active Record. ([@nvasilevski][]) @@ -411,3 +412,4 @@ [@jdelStrother]: https://github.com/jdelStrother [@aesthetikx]: https://github.com/aesthetikx [@nvasilevski]: https://github.com/nvasilevski +[@skryukov]: https://github.com/skryukov diff --git a/lib/rubocop/cop/rails/reflection_class_name.rb b/lib/rubocop/cop/rails/reflection_class_name.rb index 4c1e2bfcf0..c7504934da 100644 --- a/lib/rubocop/cop/rails/reflection_class_name.rb +++ b/lib/rubocop/cop/rails/reflection_class_name.rb @@ -40,7 +40,7 @@ def on_send(node) def reflection_class_value?(class_value) if class_value.send_type? - !class_value.method?(:to_s) || class_value.receiver.const_type? + !class_value.method?(:to_s) || class_value.receiver&.const_type? else !ALLOWED_REFLECTION_CLASS_TYPES.include?(class_value.type) end diff --git a/spec/rubocop/cop/rails/reflection_class_name_spec.rb b/spec/rubocop/cop/rails/reflection_class_name_spec.rb index abd62608dd..51caf666f7 100644 --- a/spec/rubocop/cop/rails/reflection_class_name_spec.rb +++ b/spec/rubocop/cop/rails/reflection_class_name_spec.rb @@ -59,6 +59,12 @@ RUBY end + it 'does not register an offense when using `class_name: to_s`' do + expect_no_offenses(<<~'RUBY') + has_many :accounts, class_name: to_s + RUBY + end + it 'does not register an offense when using `foreign_key :account_id`' do expect_no_offenses(<<~RUBY) has_many :accounts, class_name: 'Account', foreign_key: :account_id