Coding⏱️ 3 min read📅 2026-06-03

How to Fix: What is causing this ActiveRecord::ReadOnlyRecord error?

The issue is caused by the use of `joins` in the query. When using `joins`, Rails assumes that all conditions are on the joined table, not the main table. To fix this, remove the `joins` option and instead use a subquery or a join with an `inner` keyword.

Quick Answer: Replace `joins => [:card]` with `inner => :card` to ensure conditions are applied correctly.

The ActiveRecord::ReadOnlyRecord error occurs when you try to perform an action on a record that is read-only, meaning it cannot be modified or updated. In this case, the error is caused by trying to join with a table that has a condition that always evaluates to true, making the associated records read-only.

This issue affects developers who are working with associations in Rails and try to perform actions on records that are part of a join condition.

💡 Why You Are Getting This Error

  • The primary cause of this error is trying to join with a table using a condition that always evaluates to true. When you use `joins => [:card]` and `conditions => ['deck_cards.deck_id = ? and cards.start_card = ?', @game.deck.id, true]`, the associated records are read-only because the `start_card` column is set to `true` in all cases.
  • Another possible cause of this error is that you are trying to perform an action on a record that has been marked as read-only. For example, if you try to update a record using `update_attributes`, and the record has been marked as read-only, you will get this error.

🔧 Proven Troubleshooting Steps

Optimizing the Join Condition

  1. Step 1: Change the join condition to only include records that match the condition. In this case, since `start_card` is always set to `true`, you can remove it from the conditions.
  2. Step 2: Update the query to use `joins => [:card]` instead of `joins => [:card], :conditions => ['deck_cards.deck_id = ? and cards.start_card = ?', @game.deck.id, true]`. This will prevent the associated records from being marked as read-only.
  3. Step 3: Test the updated query to ensure it returns the correct results.

Using a Different Association

  1. Step 1: Try using a different association that does not involve a join condition. For example, you can use ` DeckCard.includes(:card)`. This will retrieve all deck cards and their associated cards in one query.
  2. Step 2: Update the code to use `includes` instead of `joins`.
  3. Step 3: Test the updated code to ensure it returns the correct results.

💡 Conclusion

To resolve the ActiveRecord::ReadOnlyRecord error, you can optimize the join condition by removing unnecessary conditions or using a different association. By following these steps, you can prevent this error from occurring in the future.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions