前提・実現したいこと
UserとTweetのモデル1対多で関連付けをしたうえでデータを登録しようとすると、エラーが発生します。
["Userを入力してください"]
該当のソースコード
ruby
1#### controllers/tweets_controller.rb 2class TweetsController < ApplicationController 3 4 def new 5 @tweet = current_user.tweets.new 6 end 7 8 def create 9 @tweet = current_user.tweets.new(tweet_params) 10 @tweet.tweet_id = SecureRandom.hex(10) 11 if @tweet.save 12 redirect_to root_path, notice: "ツイートしました" 13 else 14 pp @tweet.errors.full_messages #### ここでエラーが発生。 15 render :new 16 end 17 end 18 19 def show 20 end 21 22 private 23 24 def tweet_params 25 params.require(:tweet).permit(:tweet_body) 26 end 27end
ruby
1#### models/user.rb 2class User < ApplicationRecord 3 has_many :tweets, primary_key: :id, foreign_key: :created_user_id 4end
ruby
1#### models/tweet.rb 2class Tweet < ApplicationRecord 3 belongs_to :user, primary_key: :tweet_id, foreign_key: :id 4end
current_userでログインユーザー(Userモデル)を取得しています。
テーブルは
・User
id | user_name | created_at | updated_at |
---|
・Tweet
|id|tweet_id|tweet_body|created_user_id|created_at|updated_at|
|:--|:--:|--:|--:|--:|
となっています。
Tweetのcreated_user_idに、作成したUserのidを保存する前提です。
追記:
Tweetモデルのtweet_idがTweetテーブルのFKにしたいと思います。外に見える部分なので連番にしたくないからです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/22 14:27
2020/01/22 14:36
2020/01/22 14:38
2020/01/22 14:44
2020/01/22 14:47
2020/01/22 15:36 編集