【发布时间】:2015-05-27 07:07:31
【问题描述】:
在使用 Cancan 时,我无法编辑或删除评论 - 评论与工作相关。
Cancan 对于 Jobs 工作正常,但对于 Comments,编辑和删除不显示。这是因为评论显示在工作中吗?
class Comment < ActiveRecord::Base
belongs_to :job
belongs_to :user
end
class Job < ActiveRecord::Base
belongs_to :jobcategory
has_many :comments, dependent: :destroy
end
ActiveRecord::Schema.define(version: 20150522132410) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "comments", force: true do |t|
t.text "content"
t.integer "job_id"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "comments", ["job_id"], name: "index_comments_on_job_id", using: :btree
add_index "comments", ["user_id"], name: "index_comments_on_user_id", using: :btree
user ||= User.new # guest user (not logged in)
if user.admin?
can :access, :rails_admin # only allow admin users to access Rails Admin
can :dashboard
can :manage, :all
else
can :read, :all
can [ :edit, :update, :destroy ], Comment do |comment|
comment.try(:user_id) == user.id
end
can [ :edit, :update, :destroy ], Job do |job|
job.user_id == user.id
end
can :create , Comment
can :create , Job
end
- if can? :update, @comment
= link_to "Edit", edit_job_comment_path(comment.job, comment)
- if can? :destroy, @comment
= link_to "Delete", [comment.job, comment], method: :delete, data: { confirm: "Are you sure?" }
class JobsController < ApplicationController
before_action :find_job, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!,except:[:index]
def show
@comments =Comment.where(job_id: @job)
end
更新:
class CommentsController < ApplicationController
before_action :authenticate_user!
def show
end
def create
@job = Job.find(params[:job_id])
@comment = @job.comments.create(params[:comment].permit(:content))
@comment.user_id = current_user.id if current_user
@comment.save
if @comment.save
redirect_to job_path(@job)
else
render 'new'
end
end
def edit
@job = Job.find(params[:job_id])
@comment = Comment.find(params[:id])
authorize! :update, @comment
end
def update
@job = Job.find(params[:job_id])
@comment = @job.comments.find(params[:id])
if @comment.update(params[:comment].permit(:comment))
redirect_to job_path(@job)
else
render 'edit'
end
authorize! :update, @comment
end
def destroy
@job = Job.find(params[:job_id])
@comment = @job.comments.find(params[:id])
@comment.destroy
redirect_to job_path(@job)
authorize! :destroy, @comment
end
end
【问题讨论】:
-
您是否遇到任何具体错误?
-
@bunty 嗨,不,我没有收到错误消息,只是我无法在 cmets 中查看 EDIT 和 DELETE。
-
对于哪些 cmets 您看不到 EDIT & DELETE 选项?我的意思是你能看到自己创建的评论吗? bcoz根据cancan定义的能力,你看不到其他用户创建的cmets。
-
@bunty 我看不到我创建的 EDIT & DELETE 选项
-
在查看页面中,
@comment持有什么值?我认为它只需要comment
标签: ruby-on-rails ruby-on-rails-4 cancan