Railscast从头开始授权用户

所以这是我根据Railscast#386编写的授权代码。

问题是该块适用于除user_controller之外的所有控制器。 换句话说,任何用户都可以对任何其他用户进行triger editupdate操作,即使给予它的块与有利于editupdate操作的块相同。

 def initialize(user) allow :users, [:new, :create, :show] allow :sessions, [:new, :create, :destroy] allow :favors, [:index, :show] if user allow :users, [:edit, :update] do |usr| usr.id == user.id end allow :favors, [:new, :create] allow :favors, [:edit, :update] do |favor| favor.user_id == user.id end allow :acceptances, [:create, :update] do |acceptance| !acceptance.has_accepted_acceptance? end end end 

任何帮助都非常感谢:)

您已经将(user)传递给权限类。 通过再次调用它

if user... do |user|... end

你正在重新初始化传入的用户,使其nil 。 然后,您尝试为控制器#action提供nil用户权限,在这种情况下涉及用户帐户的任何内容。

Ryan Bates包含涉及其他模型的权限块的原因是因为模型实例尚未传递给权限类。 这就是你看到以下内容的原因:

 allow_action :topics, [:new, :create, :index] allow_action :topics, [:edit, :update, :show] do |topic| topic.author_id == user.id end allow_attr :topic, [:title, :content] 

上面的这一位授予用户可能或已经创建的所有主题的权限。

解决方法取出重新初始化(user)任何内容,然后重试。

 allow_action :users, [:edit, :update] allow_attr :users, [:email, :invite_token, :name, :surname, :password, :password_confirmation] 

注意我已根据Ryan在Railscast中的建议将allow action重命名为allow_action 。 我还将allow_param方法重命名为allow_param ,因为我们习惯使用attr_accessible。