Samuel
Samuel

Reputation: 543

Rails - Comparison on the last 3 updated records of Model

I'm having issue with a comparison in Ruby on Rails. I want to check if a fullname is the last 3 updated records in the database. For some reason it checks the whole database.

if Playlist.where(fullname: @last_fullname).order(updated_at: :desc).limit(3).exists?
  puts "records exists in last 3 updated records"
else
  puts "record not found"
end

Not sure if the syntax is correct or should be broken up. It doesn't give me an error but the result is not what is expected.

EDIT: the expected result is that when a record is not within the last 3 updated then it should give "record not found". If the record is within the last 3 updated it should give "record exists in last 3 updated records".

What I'm getting when the @last_fullname exists in the database is that it will always give "records exists in last 3 updated records" eventhough it's not in the last 3 updated.

I'm only getting "record not found" when it doesn't exits in the database.

Any idea?

Upvotes: 0

Views: 71

Answers (1)

Cristian Bica
Cristian Bica

Reputation: 4117

You can achieve this at database level only with subqueries: select last 3 records and from those last 3 records search for fullname. What your example query does is search for all records with the given fullname and sorts by updated_at. Given that you only require 3 records you could do this in user space:

Playlist.order(updated_at: :desc).limit(3).any?{ |playlist| playlist.fullname == @last_fullname }

Upvotes: 4

Related Questions