LoginSignup
2
1

More than 3 years have passed since last update.

【Rails】APIモードでcookieを使う

Last updated at Posted at 2020-05-29

環境

  • Rails 5.2.3

前提

または

  • ActionController::APIを継承して API用のcontrollerを使っている。

問題/やりたいこと

そのままでは cookiesにアクセスできないので、アクセスできるようにしていきます。

やり方

ここでは後者(ActionController::APIを継承して API用のcontrollerを使っている)前提とします。

ActionController::Cookies を include する

ActionController::APIを継承しているベースコントローラー、または実際にcookiesにアクセスしたいコントローラーでinclude ActionController::Cookiesします。

つまり

  class YourApiBaseController < ActionController::API
    include ActionController::Cookies

または

  class YourApiController < YourApiBaseController
    include ActionController::Cookies

アプリケーションで ActionDispatch::Cookies を使えるようにする

config/application.rb
module YourApi
  class Application < Rails::Application
    config.middleware.use ActionDispatch::Cookies

その他

別途 session_storecredentials.yml.enc (旧バージョンの場合は secrets.yml* )の設定はされている必要があります。

config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store, key: 'your-cookie-key-comes-here'
2
1
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
2
1