以下のように、UserとTweetのモデルを作成し、関連付けをしました。
ruby
1## User.rb 2class User < ApplicationRecord 3 has_many :tweets 4end
ruby
1## Tweet.rb 2class Tweet < ApplicationRecord 3 belongs_to :user 4end
そして、TweetsControllerでレコードを作成しようとしました。
ruby
1## TweetsController.rb 2class TweetsController< ApplicationController 3 4 def new 5 @tweet = Tweet.new 6 end 7 8 def create 9 @tweet = current_user.tweets.new(tweet_params) 10 if @tweet.save 11 redirect_to root_path 12 else 13 render :new 14 end 15 end 16 17 ~ 省略 ~ 18 19 private 20 21 def tweet_params 22 params.require(:tweet).permit(:body) 23 end 24end 25
すると、
ActiveRecord::RecordInvalid (バリデーションに失敗しました: Userを入力してください):
というエラーがでました。
current_userでは確実にログインユーザー(Userモデル)の情報を取得できています。
なぜ失敗するのでしょうか?
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/22 11:37
2020/01/22 11:49 編集
2020/01/22 11:54