Created
May 12, 2014 14:34
-
-
Save taizawa/196ca09f952c44d00fc0 to your computer and use it in GitHub Desktop.
GrapeでAPIを構築時のメモ ref: http://qiita.com/taizawa/items/a5cce420298e92b046aa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment