17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GrapeでAPIを構築時のメモ

Last updated at Posted at 2014-05-12

基本的な構成や手順は後で。とりあえずつまったところをメモ。

こんなModelで

class Post < ActiveRecord::Base
  has_many :post_relationships
  has_many :categories, through: :post_relationships
  validates :name, presence: true
  accepts_nested_attributes_for :categories
end

class PostRelationship < ActiveRecord::Base
  belongs_to :post
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :post_relationships
  has_many :posts, through: :post_relationships
end

##上記のようなモデルで多対多のリレーションを含めた形で結果を返す

# api.py
module API
  class Base < Grape::API
    prefix 'api'
    version 'v1', using: :path
    format :json

    mount Post_API
  end
end

# post_api.py
class Post_API < Grape::API
  resource :posts do

    # http://localhost:3000/api/v1/posts
    get do
      # Post.all() ←これだとカテゴリーの中身が返らない。
      # これでカテゴリー含めて返る
      Post.all()as_json(include: :categories)
    end

    # http://localhost:3000/api/v1/posts/1
    get ':id' do
      Post.find(params[:id])
    end
  end
end
17
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?