Reputation: 2753
I want to set @community_topic.comment_threads.last.created_at
into last_comment_time
when @community_topic.comment_threads.last.created_at
is not nil
When it's nil, I want to set commentable.created_at
instead.
How can I write? I tried this but I've got error back:(
last_comment_time = @community_topic.comment_threads.last.created_at || commentable.created_at
Upvotes: 0
Views: 71
Reputation: 29880
Personally I think this is more readable than the ternary operator.
last_comment_time =
if @community_topic.comment_threads.last.created_at.nil?
commentable.created_at
else
community_topic.comment_threads.last.created_at
end
More lines are not necessarily a bad thing if you are sacrificing clarity.
As far as your code:
last_comment_time = @community_topic.comment_threads.last.created_at || commentable.created_at
This is the best way to do it. You are most likely getting an error because .last
is returning nil
(this is what happens when there are no records in the scope it's being called on). So in this case it is likely that you don't have any threads under the @community_topic
.
Ruby offers a method called try
, which will call a method and return nil
if the method is being called on Nil::NilClass (as opposed to throwing a NoMethodError exception).
This can be used in your line of code like this:
last_comment_time = @community_topic.comment_threads.last.try(:created_at) || commentable.created_at
So last
will return nil, then try to call created_at
. Because created_at
is being called on nil using try
, it will also return nil and so the variable will be set to commentable.created_at
.
Upvotes: 3
Reputation: 3937
last_comment_time = @community_topic.comment_threads.last.created_at.nil? ? commentable.created_at : @community_topic.comment_threads.last.created_at
Interestingly, there is a conditional operator
tag on Stack Overflow that explains how the conditional operator works:
"The conditional operator, represented by the characters ? and :, is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is also commonly referred to as the ternary operator or inline if. It is used as follows: (condition) ? (value...)"
The : would then stand in for else
.
Upvotes: 1