有Permission Model,没有相关的db表,用于授权。使用 before_filter 授权方法创建新的权限对象,这取决于用户和可选的 test_id(另一个模型)。这个想法是它检查测试是否属于用户,它允许这个用户删除这个测试,如果不是,它取消交易。所以我的初始化方法:
class Permission
def initialize(user, *test_id)
@user = user
if !test_id.empty?
test_id.each do |t|
test = Test.find_by_id(t) #finding real test record
self.instance_variable_set(:"@test_#{t}", test) #should set @test_{id}
#an instance of this new permission refering to actual test record
end
end
allow :users, [:new,:create]
allow :root,[]
allow :session, [:create, :destroy]
allow :tests, [:new, :create]
if !test_id.empty?
for i in 0...test_id.length
t = self.instance_variable_get(:"@test_#{i}") #getting this test record.
if t.user_id == @user.id
allow :tests, [:edit,:lock,:unlock, :destroy ]
end
end
end
end
问题是 rails 得到的结果instance_variable_get
是 nil。所以要么我设置实例@test_{id} 错误,要么得到它。提前致谢