Take the tour ×

I am working a report that counts neighbors in a household - I am looking at using either a helper method, simple query or both

A household is an object that has several neighbors and I want to count the total number of neighbors in a select group of households. I have an array of households IDs:

@household_ids = [31, 15, 30, 38, 1, 5, 32, 25, 10, 26, 14,29]

I tried this:

def household_neighbor_count(houses)
   houses.each  do |id| 
   @neigh  = Household.find(id).neighbor_count

Which doesn't work - it returns a list of the IDs

Since this is Rails I could also do an activerecord query and this is my shot in pseudo sql:

 Neighbors where household_id == household_id in @household-ids

I am using squeel if that helps

How do I do this either -approach is fine or a recommendation of the best approach is great

share|improve this question
add comment

3 Answers

up vote 0 down vote accepted

It is unclear what you are trying to do, but I guess this is what you want:

houses.map{|id| Household.find(id).neighbor_count}.inject(:+)

If there are duplicates within the neighbors among the houses, then you need a method to get the set of neighbors for a given house, not just the count. And since you have not shown such method, I guess either that is not an issue, or your question is inappropriate.

share|improve this answer
add comment

Asuming there are household_id in Neighbor model

total_number_of_neighbors = Neighbor.where('household_id IN (?)', @household_ids).count
share|improve this answer
add comment

try this out

Household.includes(:neighbors).select('households.id, neighbors.id').where(:id => [31, 15, 30, 38, 1, 5, 32, 25, 10, 26, 14,29]).map{|r| {r.id =>  r.neighbors.count}}
share|improve this answer
add comment

Your Answer


