以下のような手段があるようです。
http://rails-bestpractices.com/posts/47-fetch-current-user-in-models
ActiveScaffoldを使っていれば、以下のようにcontrollerにcurrent_userメソッドを定義すれば、
modelでcurrent_userが使えるようになります。
以下のような感じです。
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protected
def current_user
User.find(session[:user_id])
end
end
app/models/aaa.rb
class Aaa < ActiveRecord::Base
def set_user_info
self.user_name = current_user.name
end
end
みたいな感じです。
以下が参考になります。
http://www.ibm.com/developerworks/jp/linux/library/l-activescaffold/
https://github.com/activescaffold/active_scaffold/wiki/Security
current_userがモデルで使えるようになる処理は
lib/active_scaffold/active_record_permissions.rb
に記載されています。
ざっくりとした仕組みとしては、以下のような感じのことが行われているようです。
#モデル相当のもの
class Moo
class << self
attr_accessor :test_func
end
def current_user
Moo.test_func.call
end
end
#コントローラ相当のもの
class Con
attr_accessor :val
def set_mod_func
Moo.test_func = proc { p "========#{@val}" }
end
end
c = Con.new
c.val = "111"
m = Moo.new
m.current_user
NoMethodError: undefined method `call' for nil:NilClass
c.set_mod_func
m.test
"========111"
ちなみに、このブログでactive_scaffoldに関しての情報を他にも乗せています。
ActiveScaffoldの小ネタのまとめ
0 件のコメント:
コメントを投稿