こんにちは
今Railsで簡単なSNSアプリを作っているんですがご教授願いたいことがあります
Deviseでログイン機能を持たせて会員者のみ投稿、コメント可
投稿にはDeviseユーザーのIDを引っ張って来ることがこのような形で出来ました
投稿のコントローラー
Ruby
1def create 2 @tweet = Tweet.new(tweet_params) 3 @tweet.user_id = current_user.id 4 if @tweet.save 5 redirect_to tweet_path(@tweet) 6 else 7 render :new 8 end 9end
ですがそのTweetに紐づけているコメントにコメントした人のDeviseのIDやユーザー名を取得する方法がわかりません
このように記述してみましたがエラーを見る限りIDはNilになります
コメントのコントローラー
Ruby
1def create 2 @tweet = Tweet.find(params[:tweet_id]) 3 @comment = Comment.new 4 @comment.user_id = current_user.id 5 @tweet.comments.create(comment_params) 6 redirect_to tweets_path(@tweet) 7end
コメントのView
HTML
1<%= link_to user_path(@tweet.user_id) do %> 2 <%= @tweet.user.username %> 3<% end %>
@tweet.comments = などに変えてみたのですが結果は変わらずNilでした
どうすればコメントした人のDeviseで登録したIDやユーザー名を表示させることができるのでしょうか
必要なファイルを言っていただければ提示いたします
追記
Userモデル
Ruby
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 mount_uploader :avatar, AvatarUploader 8 has_many :tweets, dependent: :destroy 9 has_many :comments, dependent: :destroy 10end 11
Tweetモデル
Ruby
1class Tweet < ApplicationRecord 2 mount_uploader :image, ImageUploader 3 belongs_to :user 4 has_many :comments, dependent: :destroy 5 6 7 validates :title, presence: true 8 9 validates :body, presence: true 10 11 12end 13
Commentモデル
Ruby
1class Comment < ApplicationRecord 2 mount_uploader :image, ImageUploader 3 belongs_to :tweet 4 belongs_to :user 5end 6
回答2件
あなたの回答
tips
プレビュー