1

I have done simple Rails finds for two tables, but now find that with a 4 table query I am not making good progress. All tables are connected with keys and are basically:

  • User (has many)
  • Phones (has many)
  • Campaigns (has many)
  • Calls

I just want to count the total number of calls a specific user has and the total number of calls for a specific campaign. I could also add user-id to Campaigns and Calls but for some reason I think that cheating or a bad idea. I just don't know.

2 Answers 2

1

Rails 3:

Total number of calls a specific user has:

@user.phones.joins(:campaigns => :calls).count

Total number of calls for a specific campaign:

@user.phones.joins(:campaigns => :calls).where('campaigns.id' => @campaign.id).count
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming that a phone belongs to a user, and a campaign belongs to a phone:

# total calls for a specific campaign
campaign_call_count = Campaign.find(id).calls.count
# or a report for all campaings
Campaign.all.map{|c| "#{c.name}: #{c.calls.count}"

#total calls a user has
user_phone_ids = user.phones.map(&:id)
user_calls_by_campaign = Campaign.where(:phone_id=>user_phone_ids).map{|campaign| "#{user.name} calls for #{campaign.name}: #{campaign.calls.count}" }
puts user_calls_by_campaign

That should give you a list

2 Comments

Not sure what the "&" is, so when things settle a little I will go and figure out this new-to-me thing. Thanks for the response, wish I could pick top top answers!
map(&:id) is syntax sugar for map{|user| user.id}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.