0

関連する db テーブルを持たない Permission Model があり、認可に使用されます。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が nil であることです。または、インスタンス @test_{id} を間違って設定したか、取得しました。前もって感謝します

4

3 に答える 3

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
于 2013-04-11T19:44:31.677 に答える
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

正常に動作します

于 2013-04-11T19:42:21.723 に答える
0

変数名自体に基づく主キーを持つデータベースとしてインスタンス変数を使用しています。言うまでもなく (私が思うに?)、これは良い習慣ではありません。を使用instance_variable_setして動的なインスタンス変数名を設定できますが、一般に、データに関して動作がどのように実装されているかを追跡することがより困難になるため、これによりクラスが予測不能になると思います。

インスタンスに多数のオブジェクトをキャッシュする必要がある場合は、配列やハッシュなどのデータ構造を使用して、それを独自のインスタンス変数に設定できます。

于 2013-04-11T19:44:50.460 に答える