Most recent has_one from a has_many

I have a company model with a key (domain). I have a contact model which also has a domain.

I have successfully setup a has_many relationship between these two.

has_many :contacts, class_name: 'Contact', primary_key: 'domain', foreign_key: 'domain' 

Each contact has a date field on it. I'd like a relationship which gets me the most recent contact (by date) from the contacts relationship.

Is this possible?

I'm aware I could do something like:

def most_recent_contact   contacts.order('date desc null last').first end 

Is this the best way? Is it the rails way? Open to suggestions.

Replay

Well, this seems to be ONE way, but it doesn't "reuse" the relationship (it repeats it)...

has_many :contacts, class_name: 'Contact', primary_key: 'domain', foreign_key: 'domain'
has_one  : most_recent_contact, -> { order date:  :desc }, class_name: 'Contact', primary_key: 'domain', foreign_key: 'domain'

Category: ruby on rails Time: 2016-07-28 Views: 0

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.278 (s). 12 q(s)