Search code examples
ruby-on-railshas-many

In Ruby on Rails, how can I create a has_many relation for "previous records"?


Let's say I have a User model and a Contact model. And I have the following relations in the user.rb class:

has_many :contacts
has_one :most_recent_contact, -> { order(created_at: :desc }

I saw this answer: https://stackoverflow.com/a/38647605/1218280 and I got thinking:

What if I wanted to add a has_many :previous_contacts relationship?

So if the user had 5 contacts, the has_many :contacts would return an array of all 5, the has_one :most_recent_contact would return a single contact, and has_many :previous_contacts would return an array of 4 contacts.

Granted, I can do this inefficiently with something like:

def previous_contacts
  contacts - [most_recent_contact]
end

But I'm wondering if I could accomplish the same thing with a has_many relation, which reads better (to me)

Thoughts?


Solution

  • You can use offset to skip the first record:

    has_many :previous_contacts, -> { order(created_at: :desc).offset(1) } ...