Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6194395
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T03:17:23+00:00 2026-05-24T03:17:23+00:00

I have a model in the database. The model has 3 keys of interest:

  • 0

I have a model in the database. The model has 3 keys of interest:

created_at, type, key

  • created_at, is, well, the timestamp
  • type is a known enumeration.
  • key follows a convention, but in general is unknown and non-unique.

There are potentially hundreds of records with a given type and key combination, and the records are potentially not small. I’m trying to avoid loading them from the database as much as possible.

The problem is to efficiently find the latest version of an object (without having to delete old versions). I want to get the latest record from the database for each key of a type, but I do not know what the keys are. The query is that I give a type, I end up with a Hash of objects [key => object] where the object I select for the hash is the newest object (most recent created_at value) with that key-type pair.

My first thought was to do this in memory

 # this is pseudo code, have not compiled
 models = Model.where(:type => :some_type).order("created_at desc")
 result = models.inject(Hash.new) {|r, m| r[m.key] = m unless r.has_key? m.key}

But this is going to get ugly big as I scale. Second thought is to get all the keys then query for all the models. Something like:

 keys = Model.where(:type => :some_type).select("DISTINCT key").map{|m| m.key }
 result = keys.inject(Hash.new) {|r, k| r[k] = Model.where(:type => :some_type).where(:key => k).order("created_at").last; r }

But, as I’m writing this code, I just keep thinking, there’s gotta be a better way. This solution would case me to potentially do a lot of queries to the database as things grow. At some point, I’ll have to cap the keys anyway, so if you can suggest a solution that lets me limit/paginate the results, better still.

So, is there a way to do this more efficiently? Maybe a magic search param in Arel or keyword in SQL I’ve forgotten about?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T03:17:24+00:00Added an answer on May 24, 2026 at 3:17 am

    I would use a separate table that records the ID of the latest record in a separate table, ie.

    class Model
      after_create :update_latest_record
    
      def update_latest_record
        if latest_model = LatestModelLookup.where(:type => self.type, :key => self.key)
          latest_model.update_attributes(:model_id => self.id)
        else
          LatestModelLookup.create(:type => self.type, :key => self.key, :model_id => self.id)
        end
      end
    end
    

    You’ll need to have an index on LatestModelLookup(type, key) (and probably LatestModelLookup(type))

    So when you need to query the latest records by key for a type, you would have to do:

    model_ids = LatestModelLookup.where(:type => type).select('model_id').map(&:model_id)
    result = Model.find(model_ids).inject({}) { |res, rec| res[rec.key] = rec }
    

    The benefit of having a separate table is that the overhead of updating the indices on LatestModelLookup are pretty low. The indices will only change when a new record for a distinct [type, key] are added.


    edit: conditional was reversed

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have 3 database model - Semester, Section and Notecard The Notecard model has
I have category model that has a tree structure. In my database I have
Currently I have a database of Courses, and it has 6 columns: class Course(models.Model):
Currently I have a database object, vacancies which has a column (foreign key) CareerLevels.
I have a model that looks like this (well not really but it has
I have a model, Foo . It has several database properties, and several properties
I have a Rails model called Person which has database table columns for first_name
I have a database-first model generated with full primary keys. Database first model works
I have a model on top of my database model and map the objects
I have a model where I select the proper data from database as below:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.