LoginSignup
17
19

More than 5 years have passed since last update.

Railsでsession管理にactive_recordを使う方法と型の注意点(特にフォームが多い時とかに)

Last updated at Posted at 2014-11-25

Railsでsessionをactive_recordを使って管理をするときにちょっとデータベースの型で詰まったのでメモします。

環境

Ruby 2.1.2
Rails 4.1.6
MySQL

+-------------------------+----------+
| Variable_name           | Value    |
+-------------------------+----------+
| version                 | 5.6.21   |
| version_comment         | Homebrew |
| version_compile_machine | x86_64   |
| version_compile_os      | osx10.10 |
+-------------------------+----------+

activerecord-session_store

gem activerecord-session_store を入れる。Gemfileに追記してbundle installします。

Gemfile
gem 'activerecord-session_store'

active_recordをsession_storeに設定

次にsession_store.rbで:active_record_storeを設定します。デフォルトでは:cookie_storeとなっています。

config/initializers/session_store.rb
Railsapp::Application.config.session_store :active_record_store, key: '_railsapp_session'

マイグレーション

セッションを管理するテーブルを作ります。

bundle exec rails generate active_record:session_migration
xxx_add_sessions_table.rb
class AddSessionsTable < ActiveRecord::Migration

  def change
    create_table :sessions do |t|
      t.string :session_id, :null => false
      t.text :data, limit: 4294967295
      t.timestamps
    end

    add_index :sessions, :session_id, :unique => true
    add_index :sessions, :updated_at
  end

end

マイグレーションファイルが作られますがここで自分の環境ではですが注意すべきことありました。最初、dataカラムを普通にtext型だけでやっていたのですが、それだとフォームが多すぎるせいか以下のエラーが頻発しました。データが大きすぎるそうです。

 Data too long for column '' at row 1

なので、MySQLのlongtext型をつかうためにtextにlimitを設定しました。

xxx_add_sessions_table.rb
t.text :data, limit: 4294967295

ちなみに

1 to 255 bytes: TINYTEXT
256 to 65535 bytes: TEXT
65536 to 16777215 bytes: MEDIUMTEXT
16777216 to 4294967295 bytes: LONGTEXT

だそうです。
こうしたらエラーはでなくなりました。
あとはmigrate実行してOKです。

bundle exec rake db:migrate

再起動はしといてください。

参考

Rails4でsession storeをActiveRecordに変更 | EasyRamble
http://easyramble.com/rails-active-record-session-store.html
Rails 3 Migration with longtext - Stack Overflow
http://stackoverflow.com/questions/4443477/rails-3-migration-with-longtext

17
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
19