現在Bloggerのような機能をRailsで作成しています。
ユーザは複数のコメントを持ち、記事にコメントをつけます。(Article)
複数のコメントは一人のユーザーに帰属し、コメントも1つのユーザーに帰属するという関係です。(Comment)
また、コメントにはCarrierWaveで格納した画像を紐付けています。(CommentImage)
- comment.rb
Ruby
1class Comment < ApplicationRecord 2 belongs_to :user 3 belongs_to :article 4 has_many :comment_images 5 accepts_nested_attributes_for :comment_images 6 7 default_scope -> { order(created_at: :desc) } 8 validates :user_id, presence: true 9 validates :article_id, presence: true 10end
- comment_image.rb
ruby
1class CommentImage < ApplicationRecord 2 belongs_to :comment 3 mount_uploader :image, ThumbnailUploader 4end
エラーが発生しているのは、コメントを実際に投稿しようと思うと、なぜかうまくいかないのです。エラー表示はありませんが、コメントがうまく保存されず「コメントの投稿に失敗しました」というアラートが出てしまいます。
- comment_controller.rb
ruby
1class CommentsController < ApplicationController 2 def create 3 @comment = current_user.comments.create(create_params) 4 if @comment.save 5 flash[:success] = "コメントが投稿されました!" 6 redirect_to root_path 7 else 8 flash[:alert] = "コメントの投稿に失敗しました。" 9 redirect_to root_path 10 end 11 end 12 13 def show 14 @comment = comment.find(params[:id]) 15 end 16 17 def new 18 @comment = Comment.new 19 @comment.images.new 20 end 21 22 def destroy 23 @comment.destroy 24 flash[:success] = "コメントが削除されました" 25 redirect_to request.referrer || root_url 26 end 27 28 def edit 29 end 30 31 def update 32 end 33 34 private 35 36 def create_params 37 params.require(:comment).permit(:id, :content, :title, :article_id, :user_id, comment_images_attributes: [:image]) 38 end 39 40 def correct_user 41 @comment = current_user.comments.find_by(id: params[:id]) 42 redirect_to root_url if @comment.nil? 43 end 44end
ビューの表示は、comment/newではなく、articles/show内で行っています。
ruby
1 <%= form_for(@comment) do |f| %> 2 <%= f.hidden_field :article_id, value: @article.id %> 3 <!-- ここにコメントの内容が入ります --> 4 <label>コメントを入力</label> 5 <%= f.text_area :content, placeholder: "コメント内容", rows: "5" %> 6 <label>画像を投稿</label> 7 <!-- ここに写真添付が入ります --> 8 <%= f.fields_for :images do |comment_image| %> 9 <%= comment_image.file_field :image %> 10 <% end %> 11 </div> 12 <%= f.submit "投稿する" %>
*articles_controllerを下記に追記します。
ruby
1class ArticlesController < ApplicationController 2 before_action :set_article 3 4 def show 5 @comment = current_user.comments.build if signed_in? 6 end 7 8 private 9 10 def set_article 11 @article = Article.find(params[:id]) 12 @comment = Comment.new 13 @comment.comment_images.new 14 end 15end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/03 05:04
2017/07/03 05:19 編集
2017/07/04 00:28
2017/07/04 00:31
2017/07/04 00:51
2017/07/04 05:06