これで、ユーザーが自分のレールフォーラムの投稿に画像を追加できるようになりました。私は今、ユーザーがコメントに画像を投稿に追加できるようにしたいと考えています。ここでユーザーがRailsフォーラムのコメントに画像を追加する機能
= simple_form_for([@post, @post.comments.build]) do |f|
= f.input :comment
= f.input :image
%br
= f.submit
posts_controllerファイルである:ここで
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@posts = Post.all.order("created_at DESC").paginate(page: params[:page], per_page: 7)
end
def show
end
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :content, :image)
end
エンド
はcomments_controllerである私は、ビューファイルを編集
class AddAttachmentImageToComments < ActiveRecord::Migration
def self.up
change_table :comments do |t|
t.attachment :image
end
end
def self.down
remove_attachment :comments, :image
end
end
移行add_attachment_image_to_comments.rbから始まった ファイル:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:comment, :image))
@comment.user_id = current_user.id if current_user
@comment.save
if @comment.save
redirect_to post_path(@post)
else
render 'new'
end
end
def edit
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
end
def update
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
if @comment.update(params[:comment].permit(:comment, :image))
redirect_to post_path(@post)
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
end
これにより、ユーザーは添付ファイルを追加できます。私が今問題にしているのは、画像を投稿のコメントセクションに表示することです。 これは私のショーファイルです:
#post_content
%h1= @post.title
%p= @post.content
= image_tag @post.image.url(:medium)
#comments
%h2
= @post.comments.count
Comment(s)
= render @post.comments
= image_tag @comment.image.url(:medium)
私はエラーを取得 - nilのための未定義のメソッド `画像」:NilClassを。この行のハイライト - = image_tag @ comment.image.url(:中)
ご迷惑をおかけして申し訳ありません。
質問を関連するコントローラのアクションコードで更新できますか? – Pavan
リマインダーをありがとう。 comments_controllerファイルを追加しました。 – Sapsford11
そのコードを持つビューページの名前は何ですか? – Pavan