Donato
Donato

Reputation: 2777

maintain activerecord relation when accessing relations through collection

I have an activerecord relation object called contacts. Each contact model has_one lead. I want to return the leads as a relation and therefore I cannot use map,collect,select.

Obviously, this doesn't work because the iterator breaks the relation:

contacts.select(&:lead)

This works but returns contacts as the relation object, not leads:

contacts.joins(:lead)

Therefore when I try to invoke the group_by_week activerelation method on the result:

contacts.joins(:lead).group_by_week(:created_at).size

created_at refers to contacts, whereas I want it to refer to leads.

Upvotes: 0

Views: 60

Answers (1)

j-dexx
j-dexx

Reputation: 10406

I'd just do it like this:

leads = Lead.where(contact_id: contacts)

If that fails you might need to select the id's of the contacts and pass those in.

leads = Lead.where(contact_id: contacts.map(&:id))

Upvotes: 0

Related Questions