undefined method `user' for nil:NilClass

三世轮回 提交于 2019-12-12 03:08:56

问题


In my model email token i have

def self.token_valid(token, type)
   return unless token.present?
   token = EmailToken.where("token = ? and verification_type = ? and confirmed = 'false' and created_at <= ?", token, type, EmailToken.expires).includes(:user).first
   user = token.user
 end

And I call this method from my controller

def confirm_password_reset
    @user = EmailToken.token_valid(params[:pass_reset],"password")
    render 'reset_password' if @user
end

The conditions are valid because I've tested it without trying to associate it with the user and it works. What I'm trying to do is to get token_valid method to confirm the token and return both the token and it's associated user. The belongs_to and has_many del have also been defined.
Current error : undefined method user for nil:NilClass
Thanks.


回答1:


The best way to go about this is to make your model return token, then in your reset_password view inspect the @user obj

<%= @user.inspect %>

My guess is that it returns and empty array. If you're using sqlite you might want to read this ref doc about boolean data types in sqlite. So you might want to change your confirmed field to 0 for false and 1 for true.

token = EmailToken.where("token = ? and verification_type = ? and confirmed = 0 and created_at <= ?", token, type, EmailToken.expires).includes(:user).first

If not, check spelling mistakes in your tables.




回答2:


This line :

 token = EmailToken.where("token = ? and verification_type = ? and confirmed = 'false' and created_at <= ?", token, type, EmailToken.expires).includes(:user).first

returns nil.



来源:https://stackoverflow.com/questions/15383294/undefined-method-user-for-nilnilclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!