简体   繁体   中英

Policy error: undefined method id for nil:nilClass

I have a policy that's giving me trouble. I keep getting the error message

undefined method `id' for nil:NilClass

for the following policy:

def update?
    user.present? && current_user.creator?(record, current_user)
end

This is the method user.creator?:

def creator?(wiki, user)
    relationships.find_by(wiki_id: wiki.id, user_id: user.id).creator_created
end

Relationships is the join table in a has_many, through relationship between Wikis and Users. Neither Wiki nor User is nil, and Relationships shouldn't be, either. I've just seeded the database to include a Relationships record for each Wiki. When there's no User, this policy works just fine, it simply rejects whatever I've put underneath. This error only occurs when there is a user, in other words when I'm logged in as a user. So I just can't tell which class is reading as nil, and which id is a problem.

Any thoughts?

Thanks!

该策略中可能没有current_user ,这通常是Devise提供的控制器帮助器方法。

From what you posted, this looks like Pundit for authorizations. In Pundit, current_user is not the current user, user is the current user as it is passed through when using the authorize method (I assume that you defined user in your policy class as the user, if not, use the defined variable for the user). Read the Pundit docs for more information.

Replace current_user with user and you won't get that error. If you are looking to do something special with the authorization, post a comment with what you are looking to do.

I think I was calling the policy on examples that had no relationship record, so Relationship was nil. I've edited my creator? method to:

def collaborator?(wiki, user)
    if Relationship.exists?(:wiki_id =>wiki.id, :user_id => user.id)
        true
    else
        false
    end
end

and that seems to have helped. Thank you for your input!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM