i want to create a function for comments for my rails application. Therefore only the current_user or an admin (i use active_admin) should be able to delete his comment. But i have trouble to figure that one out because my methods seem to point to nil. can someone help me out please?
My comments_controller.rb
class CommentsController < ApplicationController
before_action :correct_user, only: :destroy
def create
@post =Post.find(params[:post_id])
@comment =@post.comments.create(params[:comment].permit(:name, :body))
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment= @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def correct_user
@user= User.find(current_user.id)
redirect_to(root_url) unless current_user.id == @post.comment.user.id
end
end
In my correct_user method the undefined comment shows up, so i already tried to add
@post = Post.find(params[:post_id])
@comment= @post.comments.find(params[:id])
and tried different ways to make this run.
my comment.rb
class Comment < ApplicationRecord
belongs_to :post
end
my post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 5}
validates :body, presence: true
validates :user, presence: true
validates :user_id, presence: true
has_attached_file :image #, :styles => { :medium => "300x300>", :thumb =>
"100x100>" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
and my user.rb
class User < ApplicationRecord
has_many :posts
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
Can someone help me?
PS: i want to do this rather with an before action, then with an if-statement around the delete link.
Aucun commentaire:
Enregistrer un commentaire