Rails APIのクイックアップ
チュートリアル
ステップ
1 .新規Railsプロジェクトを作成する
Railsがインストールされていると仮定して、プロジェクト名を
<my-project>
に置き換え、次のコマンドを入力します.rails new <my-project> --api --database=postgresql
Flags: The
--api
flag will forgo some of the extra junk a full Rails app has that I do not need. The--database
flag lets you specify the type of database you prefer. I chose PostgreSQL. If you do not include this flag, the default database will be SQLite.
デモのために、私は悪犬キャッチャーAPIを作成します.
Googleイメージで見つけたこの犬キャッチャーおもちゃをチェックしてください:
どのような不適応の子供は犬キャッチャーおもちゃでプレーしたいですか?イククス
2プランモデル/関係
Railsがインストールされている間、現在モデルと関係を計画する絶好の時間です.時間のこれらの明確なアイデアを持つ頭痛の多くを保存します.
私は2つのモデル、キャッチャーと犬と行きます.
関係は次のようになります.
3 .リソースを生成する
次に、リソースを生成します.このコマンドは、迅速に各モデル名のための移行、モデル、コントローラ、およびルートを設定します.
rails generate resource <model> <attribute>:<type> <attribute>:<type>
Tips: You can use
g
as shorthand forgenerate
. Also, you can list another model’s name as an attribute with a type ofreferences
to automatically add a foreign key to that model.
これらは私のリソースコマンドです.
rails g resource catcher name:string city:string
rails g resource dog name:string breed:string catcher:references
参照はドッグモデルの外部キーを与えますが、手動でキャッチャーモデルを追加してhas_many :dogs
を追加しなければなりません.class Dog < ApplicationRecord
belongs_to :catcher # set up by catcher:references
end
class Catcher < ApplicationRecord
has_many :dogs # add this line
end
データベースの作成/移行
生成されたすべてのファイルでは、データベースを取得する時間です.まず、すべての正しいファイルを確認するには、マイグレーションファイルをダブルチェックします.
class CreateCatchers < ActiveRecord::Migration[6.0]
def change
create_table :catchers do |t|
t.string :name
t.string :city
t.timestamps
end
end
end
class CreateDogs < ActiveRecord::Migration[6.0]
def change
create_table :dogs do |t|
t.string :name
t.string :breed
t.references :catcher, null: false, foreign_key: true
t.timestamps
end
end
end
Note: Notice the line under
CreateDogs
that starts witht.references...
. Becausenull: false
, I will not be able to create a Dog unless it has the foreign key of a Catcher. If you want to be able to create models without this, setnull: true
.
すべてが正しく見えるので、端末にこれらのコマンドを入力してデータベースを作成し、移行します.
rails db:create
rails db:migrate
次の手順で進捗状況をダブルチェックします端末、
rails c
またはrails console
のCatcher.create(name: 'test')
、およびドッグインスタンスDog.create(name: ‘test’, catcher_id: 1)
を作成します.エラーはないはずです.Catcher.find(1).dogs
に入ることによって関係をテストします.これは、1のIDでキャッチャーを見つけて、彼らには犬がいるならば、私を示します.私は得る<ActiveRecord::Associations::CollectionProxy [#<Dog id: 1, name: “test”, breed: nil, catcher_id: 1, created_at: “2020–10–04 06:39:15”, updated_at: “2020–10–04 06:39:15”>]>
エラーがないので、次のステップのための時間です.5 .コントローラの設定
最後のステップでは、基本的なインデックスコントローラーを設定し、Railsサーバーでテストします.
class CatchersController < ApplicationController
def index
# grab an array of all catchers in db
catchers = Catcher.all
# render a json object of all catchers
# include a sub array of their dogs with each catcher
render json: catchers, include: :dogs
end
end
私はターミナルでrails s
またはrails server
を走らせます.私はブラウザでhttp://localhost:3000/catchers
を開き、すべてが動作していることを確認します.Tip: For production purposes, you can open the CORS of this API to any website. Install the CORS gem by opening the Gemfile, uncommenting
gem ‘rack-cors’
, and runbundle install
.
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors'
Next, access the
config/application
file. Find the classApplication
and — without altering any of the default code — insert the following:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :patch, :options, :head],
:max_age => 0
end
end
Remember to change the
origins
before deployment or this API will be available to anyone.
結論
この時点で、基本的なAPIがアップされます.次の手順は、他のサイト(s)からそれをプルし、実行するためにバックエンドを実行するすべてのアクションを実行するコントローラを設定するためのコルズを開くことです.
これが役に立つという望み!主にAPIを設定するためのクイックリファレンスが欲しかったです.Railsには100万エイリアスとショートカットがあることは知っています.あなたが提案/訂正をするならば.コメントしてください、または
[email protected]
で私にメールしてください.Reference
この問題について(Rails APIのクイックアップ), 我々は、より多くの情報をここで見つけました https://dev.to/cooljasonmelton/whipping-up-a-rails-api-real-quick-mggテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol