Reputation: 598
I am upgrading a Ruby on Rails application to 5.2 from 5.0 and am receiving this error when attempting to call any of my models that have a relationship defined:
ArgumentError (A class was passed to :class_name but we are expecting a string.)
Code causing issues
belongs_to :manufacturer,
foreign_key: :org_id_mnfr,
class_name: Organization::Manufacturer
Upvotes: 1
Views: 731
Reputation: 598
The issue is with the new Rails version. Rails 5.2 no longer accepts non-quoted class names with the class_name:
attribute. You need to change all instances in which class_name:
is being passed an actual model, rather than a string of the model name.
eg.
Organization::Manufacturer
becomes 'Organization::Manufacturer'
If your application has many instances of this as mine did, you will probably want a way to automatically change these. Here is how I used Atom
editor and Regex
to find and replace all instances of this.
Find All with Regex Enabled:
Find in project: class_name: ([^'][\w|:]*[^'|,| |\n])
Replace With: class_name: '$1'
File/Directory Pattern *.rb
What this is doing:
Find all instances of class_name
that are not already quoted and capture the Class name within capture group 1. We then replace the entire find by with the static string class_name:
and then the first capture group with single quotes around it.
This results in: class_name: Organization::Manufacturer
becoming class_name: 'Organization::Manufacturer'
This can handle the class name attribute having a space , a new line
\n
, or a comma ,
character after. But there may be some instances in which this causes errors so please double check the replaces before hitting Commit!
Upvotes: 5