#実現したいこと
Rails API + React + deviseでUserを登録しています。current_api_v1_user.idをTestテーブルに登録したいのですがNoMethodError (undefined method `id' for nil:NilClass):が出てしまいuser_idが登録できません。アドバイスいただけないでしょうか。
#エラー文
Started POST "/api/v1/tests" Processing by Api::V1::TestsController#create as HTML Parameters: {"title"=>"test", "image"=>"", "body"=>"test", "test"=>{"title"=>"test", "image"=>"", "body"=>"test"}} Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms | Allocations: 660) NoMethodError (undefined method `id' for nil:NilClass):
#gemファイル
gem 'devise' gem 'devise_token_auth' gem 'rack-cors'
#Userモデル
db/migrate/devise_token_auth_create_users.rb
class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[6.1] def change create_table(:users) do |t| ## Required t.string :provider, :null => false, :default => "email" t.string :uid, :null => false, :default => "" ## Database authenticatable t.string :encrypted_password, :null => false, :default => "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at t.boolean :allow_password_change, :default => false ## Rememberable t.datetime :remember_created_at ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Lockable # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts # t.string :unlock_token # Only if unlock strategy is :email or :both # t.datetime :locked_at ## User Info t.string :name t.string :nickname t.string :image t.string :email t.text :profile ## Tokens t.text :tokens t.timestamps end add_index :users, :email, unique: true add_index :users, [:uid, :provider], unique: true add_index :users, :reset_password_token, unique: true add_index :users, :confirmation_token, unique: true # add_index :users, :unlock_token, unique: true end end
#Testモデル
db/migrate/create_tests.rb
class CreateTests < ActiveRecord::Migration[6.1] def change create_table :tests do |t| t.integer :user_id t.string :title t.string :image t.text :body t.timestamps end end end
#app/models/user.rb
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable include DeviseTokenAuth::Concerns::User has_many :tests, dependent: :destroy end
#app/models/test.rb
class Test < ApplicationRecord belongs_to :user end
#app/controllers/application_controller.rb
rails
1class ApplicationController < ActionController::Base 2 include DeviseTokenAuth::Concerns::SetUserByToken 3 4 skip_before_action :verify_authenticity_token 5 helper_method :current_user, :user_signed_in? 6 7end
#Rails(TestsController)
controllers/api/v1/tests_controller.rb
rails
1class Api::V1::TestsController < ApplicationController 2 def create 3 @test = Test.new(test_params) 4 @test.user_id = current_api_v1_user.id 5 if @test.save 6 render json: { status: 200, data: test } 7 else 8 render json: { status: 500, message: "テストの作成に失敗しました" } 9 end 10 end 11 12 private 13 def test_params 14 params.require(:test).permit(:title, :image, :body) 15 end 16end
#SessionsController
controllers/api/v1/auth/sessions_controller.rb
class Api::V1::Auth::SessionsController < ApplicationController def index if current_api_v1_user render json: { is_login: true, data: current_api_v1_user } else render json: { is_login: false, message: "ユーザーが存在しません" } end end end
#routes.rb
Rails.application.routes.draw do namespace :api do namespace :v1 do resources :tests, only: %i[index show new create edit ] mount_devise_token_auth_for 'User', at: 'auth', controllers: { registrations: 'api/v1/auth/registrations' } namespace :auth do resources :sessions, only: %i[index] end end end end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/07/08 03:03
2021/07/08 03:31
2021/07/08 04:23
2021/07/08 05:01
2021/07/08 06:05
2021/07/08 11:28
2021/07/09 03:46