我需要在Ruby on Rails应用程序中实现细粒度的访问控制.单个用户的权限保存在数据库表中,我认为最好让相应的资源(即模型的实例)决定是否允许某个用户从中读取或写入.每次在控制器中做出这个决定肯定不会很干.
问题是,为了做到这一点,模型需要访问当前用户,调用类似的东西.但是,模型通常无法访问会话数据. may_read?(current_user, attribute_name)
有一些建议可以在当前线程中保存对当前用户的引用,例如在 此博客文章中.这肯定会解决问题.
相邻的Google搜索结果建议我在User类中保存对当前用户的引用,我想这应该是那些应用程序不必同时容纳很多用户的人.;)
长话短说,我觉得我希望从模型中访问当前用户(即会话数据)来自我做错了.
你能告诉我我错了吗?
我有3张桌子
items (columns are: name , type)
history(columns are: date, username, item_id)
user(username, password)
Run Code Online (Sandbox Code Playgroud)
当用户说"ABC"登录并创建新项目时,将使用以下after_create过滤器创建历史记录.如何通过此过滤器将此用户名"ABC"分配给历史记录表中的用户名字段.
class Item < ActiveRecord::Base
has_many :histories
after_create :update_history
def update_history
histories.create(:date=>Time.now, username=> ?)
end
end
Run Code Online (Sandbox Code Playgroud)
我在session_controller中的登录方法
def login
if request.post?
user=User.authenticate(params[:username])
if user
session[:user_id] =user.id
redirect_to( :action=>'home')
flash[:message] = "Successfully logged in "
else
flash[:notice] = "Incorrect user/password combination"
redirect_to(:action=>"login")
end
end
end
Run Code Online (Sandbox Code Playgroud)
我没有使用任何身份验证插件.如果有人能告诉我如何在不使用插件(如userstamp等)的情况下实现这一点,我将不胜感激.