我正在使用 Ryan Bate 的 CanCan gem 来定义能力,但一些基本功能失败了。我有一个产品模型和产品控制器,其中我的索引操作如下所示:
def index
@req_host_w_port = request.host_with_port
@products = Product.accessible_by(current_ability, :index)
end
当我尝试使用该accessible_by
方法检索产品时出现错误,我收到此错误:
Cannot determine SQL conditions or joins from block for :index Product(id: integer, secret: string, context_date: datetime, expiration_date: datetime, blurb: text, created_at: datetime, updated_at: datetime, owner_id: integer, product_type_id: integer, approved_at: datetime)
我的能力课是这样的:
can :index, Product do |product|
product && !!product.approved_at
end
这似乎是一个非常简单的例子,所以我很惊讶它失败了,并想知道我是否忽略了一些简单的事情(即盯着我的代码太久)。
我做了更多的探索并运行了一个简单的测试。如果您查看下面的代码,一个示例工作正常,一个示例失败,它们实际上应该做同样的事情。
# This works
can :index, Product, :approved_at => nil
# This fails
can :index, Product do |product|
product && product.approved_at.nil?
end
所以问题似乎在于 CanCan 处理这些块的方式。我更深入地研究了这个库,发现了错误出现的地方——在 CanCan 的能力类定义中:
def relevant_can_definitions_for_query(action, subject)
relevant_can_definitions(action, subject).each do |can_definition|
if can_definition.only_block?
raise Error, "Cannot determine SQL conditions or joins from block for #{action.inspect} #{subject.inspect}"
end
end
end
所以我检查了这个only_block?
方法是什么。如果 can 定义有一个块但没有条件,则该方法返回 true,这对我来说没有意义,因为块的全部意义在于在块内定义条件对于以下语法来说太复杂时:
can :manage, [Account], :account_manager_id => user.id
关于这个问题的任何见解都会很棒!我还在 CanCan github 页面上提交了一个问题,但我已经到了可能需要放弃该库的地步。但是,我知道很多人都成功地使用了 CanCan,这是我认为我一定做错了什么的基本功能。特别是因为 git 存储库在 3 天前更新,并且 Ryan Bates 在 README 中提到了 Rails 3 支持。
谢谢!