いつもお世話になっております。
Ruby on RailsのAPIモードでユーザーに紐づいたTodoを作成できるようにしたいのですが、
エラーが出てしまい登録することができません。
エラー
curl -H "Content-Type:application/json; charset=utf-8" -X POST -d '{ "title":"優先"とても重要なタスクです。" }' http://localhost:3000/v1/users/todos -v -H "Authorization: 1:GTrDWExXuRhvQR6G3EBA"
上記のコマンドをサーバー起動中に、打つと下記のようなエラーが出ています。
## サーバー側 [active_model_serializers] Rendered ActiveModel::Serializer::Null with ActiveModel::Errors (0.05ms) ## ターミナル側 * Trying ::1... * TCP_NODELAY set * Connection failed * connect to ::1 port 3000 failed: Connection refused * Trying 127.0.0.1... * TCP_NODELAY set ・・・
ユーザー自体は正常にログインできているようなのですが、それに紐づくTodoが正常に投稿できていないようです。
ソースコード
app/controllers/todos_controller.rb
Ruby
1module V1 2 class TodosController < ApplicationController 3 before_action :set_todo, only: [:show, :update, :destroy] 4 5 # GET /todos 6 def index 7 @todos = Todo.all 8 9 render json: @todos.map { |todo| V1::TodoSerializer.new(todo)} 10 end 11 12 # GET /todos/1 13 def show 14 render json: V1::TodoSerializer.new(@todo) 15 end 16 17 # POST /todos 18 def create 19 @todo = Todo.new(todo_params) 20 21 if @todo.save 22 render json: @todo, serializer: V1::SessionSerializer, status: :created, location: @todo 23 else 24 render json: @todo.errors, status: :unprocessable_entity 25 end 26 end 27 28 # PATCH/PUT /todos/1 29 def update 30 if @todo.update(todo_params) 31 render json: @todo 32 else 33 render json: @todo.errors, status: :unprocessable_entity 34 end 35 end 36 37 # DELETE /todos/1 38 def destroy 39 @todo.destroy 40 end 41 42 private 43 44 # Use callbacks to share common setup or constraints between actions. 45 def set_todo 46 @todo = Todo.find(params[:id]) 47 end 48 49 # Only allow a trusted parameter "white list" through. 50 def todo_params 51 params.require(:todo).permit(:title, :deacription, :user_id) 52 end 53 end 54end
app/models/todo.rb
Ruby
1class Todo < ApplicationRecord 2 belongs_to :user 3end
app/serializers/v1/todo_serializer.rb
Ruby
1module V1 2 class TodoSerializer < ActiveModel::Serializer 3 attributes :id, :title, :description 4 end 5end
config/routes.rb
Ruby
1Rails.application.routes.draw do 2 devise_for :user, only: [] 3 4 namespace :v1, defaults: { format: :json } do 5 resource :login, only: [:create], controller: :sessions 6 resource :users do 7 resources :todos 8 end 9 end 10end
すみませんが、どうぞおたすけくださいませ。
あなたの回答
tips
プレビュー