activerecord-session_store icon indicating copy to clipboard operation
activerecord-session_store copied to clipboard

Write query attempted while in readonly mode: INSERT INTO "sessions

Open jamienourish opened this issue 4 years ago • 1 comments

Since Rails 6 we have been trying to work out what was creating errors such as Write query attempted while in readonly mode: INSERT INTO "sessions" ("session_id", "data", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"

I have spent time today and have found that this gem writes raw sql using the bypass class https://github.com/rails/activerecord-session_store/blob/b005852ea0460126bb4edd64ac03b78fbf244ead/lib/active_record/session_store/sql_bypass.rb

As the GET page request by default will use the reader DB's this is what was causing the error.

To get round this as a fix in my project I have had to create a class as the session and override save and destroy, wrapping in writer db, please not my write role is called "Writer" if you are having the same problem, please use your role name.

class ForceWriterSessionClass < ActiveRecord::SessionStore::Session

    def save
        ActiveRecord::Base.connected_to(role: :writing) do
            super
        end
    end

    def destroy
        ActiveRecord::Base.connected_to(role: :writing) do
            super
        end
    end
end

ActionDispatch::Session::ActiveRecordStore.session_class = ForceWriterSessionClass

jamienourish avatar May 26 '21 15:05 jamienourish

It still make sence with rails 6.1.4.4

vadimeremeev avatar Feb 07 '22 10:02 vadimeremeev