有权限模型,它没有相关的数据库表,用于授权。 使用before_filter authorize方法创建新的权限对象,具体取决于用户和可选的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
问题是来自instance_variable_get
的rails是零。所以我设置实例@test_ {id}是错误的,或者得到它。
提前致谢
答案 0 :(得分:2)
您在顶部设置的实例变量均为@test_{record_id}
形式。您在for循环中获得的实例变量的格式为@test_{loop_index}
。只需使用与顶部相同的循环。
test_id.each do |t|
trec = self.instance_variable_get(:"@test_#{t}") #getting this test record.
if trec.user_id == @user.id
allow :tests, [:edit,:lock,:unlock, :destroy ]
end
end
答案 1 :(得分:0)
好的,伙计们,我刚刚发现,我几乎没有复杂的东西。 在我的情况下,我真的不需要设置或获取实例变量,所以
if !test_id.empty?
test_id.each do |t|
test=Test.find_by_id(t)
if test.user_id==user.id
allow :tests, [:edit,:lock,:unlock, :destroy ]
end
end
end
工作正常
答案 2 :(得分:0)
您正在使用实例变量作为数据库,主键基于变量名称本身。不用(我想?)说,这不是一个好习惯。您可以使用instance_variable_set
来设置动态实例变量名称,但总的来说,我觉得这会使您的类无法预测,因为跟踪数据的行为实现方式更加困难。
如果需要在实例中缓存大量对象,可以使用数组结构或散列等数据结构,并将其设置为自己的实例变量。