Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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}
  ]
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした