Reputation: 5197
I want to show "not selected" when @user.user_profile.prefecture.name if [email protected]_profile.prefecture.blank?
was blank.
How can I customize this code?
@user.profile.prefecture.name if [email protected]?
Upvotes: 2
Views: 57
Reputation: 1808
Updated:
1- An object is blank if it’s false, empty, or a whitespace string
2- Unless statement code to execute unless condition false
Answer:
"Not selected" unless [email protected]?
Explain: @user.profile.prefecture.blank? will return true everytime that @user.profile.prefecture it’s false, empty, or a whitespace string for what the negation operator transforms that into false so the unless code section can be executed.
This approach it's very 'Ruby' to me and should be pretty easy to understand.
Upvotes: -1
Reputation: 239311
You could use the ternary operator, which is slightly verbose:
@user.profile.prefecture.blank? ? "Not selected" : @user.profile.prefecture.name
Or, if prefecture
is actually nil/not-nil, get rid of the blank?
:
@user.profile.prefecture ? @user.profile.prefecture.name : "Not selected"
Finally, you could get slightly more fancy with try
and ||
, which most proficient Ruby developers will find quite readable:
@user.profile.prefecture.try(:name) || "Not selected"
Upvotes: 3
Reputation: 13181
Like this
if @user.profile.prefecture.blank?
'not selected'
else
@user.profile.prefecture.name
end
Upvotes: 2