前提・実現したいこと
現在投稿アプリを作成しています。
active storage、carrierwaveを導入して画像,動画投稿を可能にしたいのですが、現在エラーが出て詰まっています。
行ったこととしては、
・active storage導入
・has_one_attachedの記述
・コントローラーで受け取る情報の定義
・ビューでの表示させる記述(エラー文参照)
になります。
rails初心者です。お力添えをよろしくお願いいたします。
発生している問題・エラーメッセージ
NoMethodError in Comments#index Showing /Users/Desktop/debate-app/debate-app/app/views/comments/index.html.erb where line #37 raised: undefined method `image' for #<Comment::ActiveRecord_AssociationRelation:0x00007f8ce24cec00>
<% end %> <% end %> <% if @comments.image.attached? %> <-ここの部分のimageです <%= image_tag @commented.image %> <% end %> <% if @comments.image.attached? %>
該当のソースコード
--commentモデル-- class Comment < ApplicationRecord belongs_to :debate belongs_to :user, optional: true belongs_to :coach, optional: true has_one_attached :image has_one_attached :video comment = Comment.last comment.video.attach( io: File.open("path/to/video"), filename: "video.txt", content_type: "text/plain" ) validates :content, presence: true, unless: :was_attached? validates :content, presence: true, unless: :is_attached? def was_attached? self.image.attached? end def is_attached? self.video.attached? end end
--commentsコントローラー-- class CommentsController < ApplicationController def index @commented = Comment.all @comment = Comment.new @debate = Debate.find(params[:debate_id]) if coach_signed_in? @comments = @debate.comments.includes(:coach) else user_signed_id? @comments = @debate.comments.includes(:user) end end def create @debate = Debate.find(params[:debate_id]) if coach_signed_in? @comment = @debate.comments.new(coach_comment_params) else user_signed_id? @comment = @debate.comments.new(user_comment_params) end if @comment.save redirect_to debate_comments_path(@debate) else @comments = @debate.comments.includes(:coach) @comments = @debate.comments.includes(:user) render :index end end private def coach_comment_params params.require(:comment).permit(:content, :image, :video).merge(coach_id: current_coach.id) end def user_comment_params params.require(:comment).permit(:content, :image, :video).merge(user_id: current_user.id) end end
補足情報(FW/ツールのバージョンなど)
文章が拙く、申し訳ございません。
もし何か不足している、知りたいコードがありましたら、コメントをお願いします。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/01/03 08:11
2021/01/03 08:17
2021/01/03 08:21
2021/01/03 08:51 編集
2021/01/03 08:53
2021/01/03 08:58
2021/01/03 09:04
2021/01/03 11:14
2021/01/03 11:15
2021/01/03 12:14
2021/01/03 12:46 編集
2021/01/03 13:14
2021/01/03 13:38
2021/01/03 15:01
2021/01/03 15:40
2021/01/03 15:54
2021/01/03 16:00
2021/01/03 16:01
2021/01/03 16:25
2021/01/04 01:01
2021/01/04 03:26