cat
cat

Reputation: 749

How can I use 'last' with order condition within 'If statement'?

I was trying to code it like this.
What's wrong with this?

def topic_button(community)
    if !community.topics.order("last_active_at DESC").last.nil? && community.topics.order("last_active_at DESC").last.last_active_at.to_date == Date.current.to_date
        'posted today'
    else
        'no post today'
    end
end

Upvotes: 0

Views: 57

Answers (3)

Logan Serman
Logan Serman

Reputation: 29880

You can use the today? method:

def topic_button(community)
  last_post = community.topics.order('last_active_at DESC').last
  if last_post && last_post.last_active_at.today?
    'posted today'
  else
    'no post today'
  end
end

Upvotes: 1

uday
uday

Reputation: 8710

 if  @community.topics.last_active_at == Date.current.to_date
        puts "posted today"
 else
        puts "no post today"
 end

Hope it helps

Upvotes: 1

user229044
user229044

Reputation: 239311

You should really just be doing the query once:

topic = community.topics.order("last_active_at DESC").last

if topic && topic.last_active_at.to_date == Date.current.to_date
   puts "posted today"
else
  puts "no post today"
end

Upvotes: 1

Related Questions