Rails: ActiveRecord::AssociationTypeMismatch: User(#1234) expected, got "42" which is an instance of String(#5678)
You assigned the wrong kind of object (or an id string) to an association.
ActiveRecord::AssociationTypeMismatch: User(#1234) expected, got "42" which is an instance of String(#5678)User expected, got Stringexpected, got which is an instance ofAssociationTypeMismatch Rails association Meaning
Assign records to associations (post.author = user) and ids to _id attributes (post.author_id = 42). Passing an id string to author= or a record of another class raises this. In forms use author_id; with strong params permit author_id not author.
Common causes
- Assigning an id to the association setter
- Wrong model class assigned
params[:author]string used for the association- Polymorphic association type mismatch
- STI class mismatch
⚡ Quick fix
post.author_id = params[:author_id]orpost.author = User.find(id)- Permit
author_idin strong params - Check the association class and STI types
Detailed fix by platform
Rails
post.author = User.find(42) # or post.author_id = 42
How to diagnose
- Assigned — Record or id?
- Class — Expected?
- Params — author_id?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- A server is already running. Check /tmp/pids/server.pid Rails: A server is already running (pid: 12345, file: /app/tmp/pids/server.pid). Exiting
- AbstractController::DoubleRenderError Rails: AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action)
- ActionController::InvalidAuthenticityToken Rails: ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity)
Most viewed in Ruby / Rails
- undefined method for nil Ruby: NoMethodError: undefined method `x' for nil (nil:NilClass)
- Bundler could not find compatible versions for gem Bundler: Bundler could not find compatible versions for gem "activesupport": In Gemfile: rails (= 7.1.0) depends on activesupport (= 7.1.0)
- FactoryBot::DuplicateDefinitionError: Factory already registered FactoryBot: FactoryBot::DuplicateDefinitionError: Factory already registered: user
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 5 Nov 2026