Fix ActiveRecord::AssociationTypeMismatch: Comment(#123) expected, got String(#456) in Rails
This error occurs when you assign the wrong type to a polymorphic association or any typed association. Rails expects an instance of the associated model class but received a different type. Ensure you assign model instances, not raw strings or IDs, and that your polymorphic type and ID columns are set correctly together.
Reading the Stack Trace
Here's what each line means:
- activerecord (7.1.3) lib/active_record/associations/association.rb:285:in `raise_on_type_mismatch!': Rails checks the type of the assigned object and raises because it does not match the expected class.
- activerecord (7.1.3) lib/active_record/associations/belongs_to_association.rb:25:in `replace': The belongs_to writer method validates the type before setting the association.
- app/controllers/reactions_controller.rb:10:in `create': The controller assigns a string where a model instance is expected.
Common Causes
1. Assigning a string instead of a model instance
Passing a string value where a polymorphic association expects a model instance.
# Reaction belongs_to :reactable, polymorphic: true
reaction = Reaction.new
reaction.reactable = 'Comment' # Should be a Comment instance, not a string
2. Setting polymorphic type and ID separately with wrong values
Setting reactable_type to a non-existent class name or mismatching ID.
reaction = Reaction.new(
reactable_type: 'Comments', # Wrong: should be 'Comment' (singular)
reactable_id: 1
)
3. Wrong association class from nested params
Nested parameters pass the wrong model type through a polymorphic form.
def create
@reaction = Reaction.new(reaction_params)
@reaction.reactable = params[:reactable_type] # Assigns a string
@reaction.save!
end
The Fix
Use safe_constantize to convert the type string to a class and validate it against an allow list. Then find the actual record and assign the model instance to the polymorphic association instead of a raw string.
def create
@reaction = Reaction.new(reaction_params)
@reaction.reactable = params[:reactable_type]
@reaction.save!
end
def create
@reaction = Reaction.new(reaction_params)
reactable_class = params[:reactable_type].safe_constantize
if reactable_class && %w[Comment Post].include?(params[:reactable_type])
@reaction.reactable = reactable_class.find(params[:reactable_id])
@reaction.save!
render json: @reaction, status: :created
else
render json: { error: 'Invalid reactable type' }, status: :unprocessable_entity
end
end
Testing the Fix
require 'rails_helper'
RSpec.describe ReactionsController, type: :request do
describe 'POST /reactions' do
let(:comment) { create(:comment) }
it 'creates a reaction for a valid reactable' do
post '/reactions', params: {
reactable_type: 'Comment',
reactable_id: comment.id,
emoji: 'thumbsup'
}
expect(response).to have_http_status(:created)
end
it 'rejects invalid reactable type' do
post '/reactions', params: {
reactable_type: 'InvalidModel',
reactable_id: 1,
emoji: 'thumbsup'
}
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
Run your tests:
bundle exec rspec spec/requests/reactions_spec.rb
Pushing Through CI/CD
git checkout -b fix/rails-polymorphic-type-mismatch,git add app/controllers/reactions_controller.rb,git commit -m "fix: properly resolve polymorphic association from params",git push origin fix/rails-polymorphic-type-mismatch
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ['5432:5432']
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.3'
bundler-cache: true
- run: bin/rails db:setup
- run: bundle exec rspec
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
gem install bugstack
Step 2: Initialize
require 'bugstack'
Bugstack.init(api_key: ENV['BUGSTACK_API_KEY'])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Fix the polymorphic assignment to use model instances.
- Add validation for allowed polymorphic types.
- Write request specs for valid and invalid types.
- Open a pull request.
- Merge and verify in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other components are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Add a database index on both the type and id columns together. Use where(reactable_type: 'Comment', reactable_id: id) for direct queries.
Yes, add a custom validation that checks reactable_type is in an allow list. This prevents malicious users from associating with unexpected models.