Skip to content

[Avram] What is the correct way to retrieve one record from db, and invoke methods on it. #1700

Answered by jwoertink
zw963 asked this question in Q&A
Discussion options

You must be logged in to vote

In Crystal, you can assign the nilable value to a variable within the if condition, and the compiler will know the type.

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 .as(User) will tell the compiler that the object is that type if a Union is possible (User | Nil).

Replies: 2 comments 13 replies

Comment options

You must be logged in to vote
13 replies
@Blacksmoke16
Comment options

@robacarp
Comment options

@zw963
Comment options

@zw963
Comment options

@zw963
Comment options

Answer selected by zw963
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants