Rails APIのクイックアップ


このブログではRuby on Rails RESTful APIを作成するための基本的な手順を簡潔に説明します.

jump to the code on GitHub


チュートリアル


ステップ

  • 新しいRailsプロジェクトを作成
  • は、モデル/関係を計画します
  • 生成リソース
  • 作成/移行データベース
  • は、コントローラ
  • をセットアップします

    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 for generate. Also, you can list another model’s name as an attribute with a type of references 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 with t.references.... Because null: 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, set null: 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 run bundle 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 class Application 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]で私にメールしてください.