gpt4 book ai didi

ruby-on-rails - 按 CanCanCan 规则中的自引用关联进行过滤

转载 作者:行者123 更新时间:2023-12-02 20:32:47 25 4
gpt4 key购买 nike

在我的项目中,我有一个 Post 类,它可以是对其他带有 self-join 的帖子的评论。除了其他规则之外,我想启用属于“已发布”帖子的帖子作为评论

我使用以下 gem :

gem 'rails', '5.0.6'
gem 'cancancan', '2.1.2'

这里是模型和能力等级

class Post < ActiveRecord::Base
belongs_to :user
belongs_to :parent, class_name: 'Post', optional: true
has_many :comments, class_name: 'Post', foreign_key: 'parent_id', dependent: :destroy
end

class User < ActiveRecord::Base
has_many :posts
end

class Ability
include CanCan::Ability

def initialize(user)
can :read, Post, parent: { status: %w(published), user: { id: user.id } }
end
end

我编写了一些 RSpec 测试,所有这些测试都应该根据上述规则通过。

RSpec.describe Ability do
subject(:ability){ Ability.new(user) }

let!(:user) { User.create }
let!(:commenter) { User.create }
let!(:post) { Post.create(user: user, parent: nil, status: 'published') }
let!(:comment) { Post.create(user: commenter, parent: post) }

# for individual objects it works
it { is_expected.not_to be_able_to :read, post } # pass
it { is_expected.to be_able_to :read, comment } # pass

# for accessible by query it fails
it { expect(Post.accessible_by(ability)).not_to include post } # pass
it { expect(Post.accessible_by(ability)).to include comment } # fail
end

当我运行 RSpec 测试时,最后一个测试失败。如果检查 SQL 日志,您可以看到它创建了正确的 JOINS,但有错误的 WHERE 语句。

SELECT (...)
FROM "posts"
LEFT OUTER JOIN "posts" "parents_posts" ON "parents_posts"."id" = "posts"."parent_id"
LEFT OUTER JOIN "users" ON "users"."id" = "parents_posts"."user_id"
WHERE "posts"."status" = 'published'
AND "users"."id" = ?

你能帮我解决一下吗?这是 CanCanCan 中的错误还是我使用 hash syntax错误吗?

最佳答案

好的,我不知道您是否可以解决这个问题,但我会尽力帮助您。

def initialize(user)
can :read, Post, id: Post.where(parent: { status: 'published', user: { id: user.id }) }
end

试试这个,然后告诉我会给你带来什么返回。

关于ruby-on-rails - 按 CanCanCan 规则中的自引用关联进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com