I have a model User which has one Subscription. Now I want to get the data in related subscription. A user may have no subscription.
This is my code:
user = Repo.get(User, 1) |> Repo.preload(:subscription)
hash = %{name: user.name, subscription_type: user.subscription.type}
So here when I try to get subscription_type, if the subscription is nil, I will get an error.
In Ruby I can use try method user.subscription.try(:type) or safe navigation operator user.subscription&.type. How about in Elixir?
One way I can think of is: user.subscription && user.subscription.type
But I feel it's redundant, any idea?