Wes Foster
Wes Foster

Reputation: 8900

Rails Get the latest child record from model instance

Contract has_many Invoices. After creating a contract, the model automatically creates an invoice depending on certain form params.

I'm wanting to be able to select the most recently created invoice from a given contract.

This what I'm wanting to achieve:

contract = Contract.new(params)
contract.save

invoice = contract.invoices.most_recent  # < wanting to get the most recent

#or possible even do this if it's quicker
invoice = contract.most_recent_invoice

Which method is most proficient and what's the best way to go about doing this? Does Rails have a built in method? I just want to learn and maintain best practices.

Thanks!

Upvotes: 0

Views: 673

Answers (3)

Иван Бишевац
Иван Бишевац

Reputation: 14641

You could try last method. Example:

contract = Contract.new(params)
contract.save

invoice = contract.invoices.last

Upvotes: 1

Amar
Amar

Reputation: 6942

Create scope for most_recent_invoice order by created_at and create limit scope which will limit the no of records(for best practise)

Upvotes: 0

Peter Brown
Peter Brown

Reputation: 51697

I would add a class method to the Invoice model that orders them by created_at and returns the first one:

class Invoice < ActiveRecord::Base
  def self.most_recent
    order('created_at DESC').limit(1).first
  end
end

invoice = contract.invoices.most_recent # => Gives the last invoice created for this contract

Upvotes: 1

Related Questions