【Railsサンプルアプリ】既存RailsプロジェクトをWebAPIに修正する (未解決)

RailsでWebAPIを作りたい。
RailsにはAPIモードがあり、rails new するときに–apiオプションを使用することで利用できる。
ただし、前回記事の通り既にプロジェクト作成済みであるため、これを修正してAPIモードにできないか調べた。
結果として、うまく修正できなかったため、次回記事の通り、–apiモードで作成し直した。
既存のRailsプロジェクトをWebAPI化
ここによると3箇所修正するとWebAPI化ができるはず。
https://railsguides.jp/api_app.html
- config/application.rb に追加
config.api_only = true
- config/environments/development.rb に追加
config.debug_exception_response_format = :api
- app/controllers/application_controller.rb の変更
class ApplicationController < ActionController::API end
ところがこれでbin/rails sしたところ、http://localhost:3000/usersでエラーが発生した。

Rendered users/index.html.erb (1146.1ms)
Completed 500 Internal Server Error in 1190ms (ActiveRecord: 5.8ms)
ActionView::Template::Error (undefined local variable or method `notice' for #<#<Class:0x00007fe155270748>:0x00007fe154e6f248>):
1: <p id="notice"><%= notice %></p>
2:
3: <h1>Users</h1>
4:
app/views/users/index.html.erb:1:in `_app_views_users_index_html_erb___1593382616114344727_70302886496880'
今の私では、これをどう直せばいいかわからないため、
このアプリは捨てて –webapiオプションで作り直すことにする。
テーブル削除
この後、–apiオプションを付加した別途作成したプロジェクトからアクセスした際、db:migrateしていない旨のエラーが出ました。しかし、既にusersテーブルはあるため、db:migrateできない。
適切な対応としては、こちらのアプリのマイグレーションファイルでdrop tableすべきだと思い、テーブル削除するマイグレーションを実行する。
$ rails g migration users
invoke active_record
create db/migrate/20181220xxxxxx_users.rb
db/migrate/20181220xxxxxx_users.rb
class Users < ActiveRecord::Migration[5.2]
def change
drop_table :users
end
end
migrationの実行
$ rails db:migrate == 20181220xxxxxx Users: migrating ============================================ -- drop_table(:users) -> 0.0249s == 20181220xxxxxx Users: migrated (0.0251s) ===================================
usersテーブルが削除されたことを確認する。
$ psql -U rails_user rails_dev
psql (11.1)
Type "help" for help.
rails_dev=# \dt
List of relations
Schema | Name | Type | Owner
--------+----------------------+-------+------------
public | ar_internal_metadata | table | rails_user
public | schema_migrations | table | rails_user
(2 rows)
「【Railsサンプルアプリ】既存RailsプロジェクトをWebAPIに修正する (未解決)」への1件のフィードバック