railsでアソシエーションをしたモデルのデータが作成できません。
Twitterのツイート機能のようなものを作っています。
親モデルがUser、その子モデルでTweetがあった場合です。
保存する際には、tweetテーブルのcreated_user_idにUserのidが保存される感じです。
ツイートすると、「Userを入力してください」というエラーが出ます。
関連付けがうまくいっていないようです。
どこが間違えているでしょうか?
ruby
1## models/user.rb 2class User < ApplicationRecord 3 has_many :tweets, foreign_key: :created_user_id 4end
ruby
1## models/tweet.rb 2class Tweet < ApplicationRecord 3 belongs_to :user 4end
ruby
1## controllers/tweet.rb 2class TweetsController < ApplicationController 3 def new 4 @tweet = Tweet.new 5 end 6 7 def create 8 @tweet = current_user.tweets.new(tweet_params) #### current_userにはログインユーザー情報(Userモデル)が入ってます。 9 if @tweet.save 10 redirect_to "/#{@tweet.id}", notice: "ツイートしました。" 11 else 12 render :new 13 end 14 end 15 16 def tweet_params 17 params.require(:tweet).permit(:tweet_detail) 18 end 19end
追記:
テーブルの構造は以下のようになっています。
・User
id | user_name | created_at | updated_at |
---|
・Tweet
|id|tweet_detail|created_user_id|created_at|updated_at|
|:--|--:|--:|--:|
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/26 04:10