Ryan-Neal Mes
Ryan-Neal Mes

Reputation: 6263

Pulling a list of related objects in a list

I have a list of contacts and each contact can has multiple interactions - these are both tables in a the databases. One contact can have many interactions

So I would load contacts and preload all the interactions. I have found that you can use includes which is great.

Now I am trying to pull a list of distinct interaction names off the list of contacts.

@contacts = Contacts.all

How can I pull all distinct interactions from this list?

I would have thought something like

@interactions = @contacts.interactions

or something to that affect

I don't want to load all interactions and work backwards since I am on the contact page.

Upvotes: 0

Views: 45

Answers (1)

Sabyasachi Ghosh
Sabyasachi Ghosh

Reputation: 2785

You write in this way

Model.include('associated_model_name').select("DISTINCT value").where('condition =?', condition)

Or you can do

Model.uniq.pluck(:column_name)

Upvotes: 2

Related Questions