※jsonのserializerはfast_jsonapiを使用。
user_serializer.rb
class UserSerializer include FastJsonapi::ObjectSerializer has_many :articles attributes :name, :email end
article_serializer.rb
class ArticleSerializer include FastJsonapi::ObjectSerializer belongs_to :user attributes :title, :contents, :status end
①gemをインストール。
gem 'sorcery'
②sorceryをインストール。
$ bundle exec rails g sorcery:install
$ bundle exec rails db:migrate
③ルーティングを設定。
namespace :api, format: 'json' do namespace :v1 do resource :authentication, only: %i[create] end end
④コントローラーを記載。
# controllers/api/v1/authentications_controller.rb module Api module V1 class AuthenticationsController < BaseController def create @user = login(params[:email], params[:password]) raise ActiveRecord::RecordNotFound unless @user json_string = UserSerializer.new(@user).serialized_json render json: json_string end private def form_authenticity_token; end end end end
確認
localhost:3000/api/v1/authentication
メールとパスワードでログイン
{ "email": "sample", "password": "sample@sample.com" }
出力結果
{ "data": { "id": "1", "type": "user", "attributes": { "name": "sample", "email": "sample@sample.com" }, "relationships": { "articles": { "data": [ { "id": "1", "type": "article" } ] } } } }
参考記事:
Rails-APIでsorceryを使ったらundefined local variable or method `form_authenticity_token'と怒られた - Qiita
Railsで超簡単API - Qiita