我有这两个模型:
class Photo < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :photos
end
以及为角色设置declarative_authorization
:
role :reg_ser do
has_permission_on :photos, :to => [:show] do
if_attribute :user_id => is { user.id }
end
end
我想允许向用户显示他上传的图像 - 仅他的图像。我的意思是,例如:
user_id | photo
1 | 1
1 | 2
1 | 3
2 | 4
当用户设置 url /photos/1
时,此图片将仅显示给编号为 1
的 user_id
,当 user_id=2
将显示此地址时,他看不到图像...
有可能做这样的事情吗?
最佳答案
你需要放一些类似的东西
filter_access_to [:index, :new, :create]
filter_access_to [:show, :edit, :update], :attribute_check => true
在你的 Controller 和类似的东西中
role :reg_ser do
has_permission_on :photos, :to => [:index, :new, :create]
has_permission_on :photos, :to => [:show, :edit: update] do
if_attribute :user_id => is { user.id }
end
end
进入 authorization_rules.rb
。因此一切正常,重要的是在 Controller 中为要检查属性的每个操作包含 :attribute_check
。
我没有使用 :index
,因为通过添加
def begin_of_association_chain
current_user
end
或类似于 Controller (这将导致 InheritedResources 将 current_user.pictures
作为集合)。
您可能也有兴趣阅读 http://asciicasts.com/episodes/188-declarative-authorization
关于ruby - 如何为每个用户设置 declarative_authorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8619316/