5
5

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.

railsのjbuilderでPOSTでjsonデータを取り込む

Posted at

routeの設定

api/todo/にPOSTしたときに、createアクションが実行されるようにroutes.rbを設定します。

config/routes.rb
  namespace :api do
    namespace :todo do
      get '/', action: 'index'
      post '/', action: 'create'
    end
  end

コントローラーの記述

jsonのデータを取り込んで、DBへ保存するようcreateアクションを記述します。

app/controllers/api/todo_controller.rb
  def create
    @todo = Todo.new(todo_params)
    respond_to do |format|
      if @todo.save
        format.json { render json: 'ok!', status: :created }
      else
        format.json { render json: 'ng!', status: :unprocessable_entity }
      end
    end
  end

  private

  def todo_params
    params.require(:todo).permit(:title, :done)
  end

POST確認

$ curl -X POST -H "Content-Type: application/json" -d '{"todo": {"title": "TESTTITLE", "done": false }}' http://localhost:3000/api/todo

doneはデフォルトでfalseです。

{
  "todo":[
    {"title":"test投稿todo","done":false},
    {"title":"test投稿2","done":true},
    {"title":"TESTTITLE","done":false}
  ]
}
5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?