- 準備
rails g model User auth_token
rails g controller Episodes
- model
class User < ActiveRecord::Base
before_create :set_auth_token
private
def set_auth_token
return if auth_token.present?
begin
self.auth_token = SecureRandom.hex
end while self.class.exists?(auth_token: self.auth_token)
end
end
- テストデータ作成
rails c
User.create
- コントローラー
class EpisodesController < ApplicationController
before_action :authenticate
def show
render text:”============show”
end
protected
def authenticate
authenticate_or_request_with_http_token do |token, options|
User.find_by(auth_token: token)
end
end
end
- routes
get ‘show’ => ‘episodes#show’
・curlでアクセス
curl http://localhost:3000/show -H ‘Authorization:Token token=”05c97536d24572ec38c1cd377652c901″‘