我正在嘗試構建一個博客,其中將有2個用戶管理員和普通用戶.Admin可以查看每個帖子和評論。而正常用戶可以查看他的唯一帖子和評論。我已經應用了我的邏輯但它不能正常工作。在我的代碼,每個用戶都可以查看對方後和評論,我不想。我已經在github上上傳了我的代碼
linkRails cancan無法正常工作
[ability.rb]
class Ability
include CanCan::Ability
def initialize(user)
unless user
else
case user.roles
when 'admin'
can :manage, Post
can :manage, Comment
when 'user'
can :manage, Post, user_id: user.id
can :manage, Comment, user_id: user.id
end
end
class PostsController < ApplicationController
before_action :authenticate_user!
authorize_resource
def index
@posts = Post.all.order('created_at DESC')
end
def new
@post = Post.new
end
def show
@post = Post.find(params[:id])
end
def create
@post = Post.new(post_params)
@post.user = current_user
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :body))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
[comment_controller]
class CommentsController < ApplicationController
authorize_resource
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment].permit(:name, :body))
@comment.user = current_user
@comment.save
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
end
[user.rb]
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
has_many :comments
end
[post.rb]
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true, length: {minimum: 5}
validates :body, presence: true
belongs_to :user
end
[comment.rb]
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
請在這裏發佈相關的代碼。 – dwenzel
請參閱我已更新的相關代碼 –
謝謝。幾個問題: 1.'case user.roles' ...不應該是'case user.role'(單數)? 2.你的邏輯在哪裏根據這個能力限制了用戶的觀點? – dwenzel