-
We assume users table, exists a Solution 1: worksopen_id = "open_id"
user : User = UserQuery.new.open_id(open_id).first # this may raise exception.
user.account
user.password_digest It works, but, first maybe raise exception instead if no matched record, so we should do rescue, right? Solution 2 worksopen_id = "open_id"
user = UserQuery.new.open_id(open_id).first? # it should be type User | Nil
return nil if user.blank?
# return nil if user.locked_at # this line code not work, because `undefined method 'locked_at' for Nil`
user.try &.locked_at But, all method invoke on user must use &, it so tediously. Solution 3 not workuser : User | Nil
user_query = UserQuery.new.open_id(open_id)
if user_query.any?
user = user_query.first
end here, user type is So, my question is, what is the correct way to do those things in varam? i am still newbie to crystal and lucky, if there is a another recommended why to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 13 replies
-
In Crystal, you can assign the nilable value to a variable within the if user = UserQuery.new.open_id("open_id").first?
# this works because Crystal compiler knows `user` exists here.
user.account
end You can also do something like if user_query.any?
user = user_query.first.as(User)
end The |
Beta Was this translation helpful? Give feedback.
-
#1700 (reply in thread) is consider as the expected answer. Thanks all! |
Beta Was this translation helpful? Give feedback.
In Crystal, you can assign the nilable value to a variable within the
if
condition, and the compiler will know the type.You can also do something like
The
.as(User)
will tell the compiler that the object is that type if a Union is possible (User | Nil
).