Skip to content

Instantly share code, notes, and snippets.

@sankage
Created November 29, 2011 01:07
Show Gist options
  • Save sankage/1402869 to your computer and use it in GitHub Desktop.
Save sankage/1402869 to your computer and use it in GitHub Desktop.
Collection Problem
# Answer model
class Answer < ActiveRecord::Base
belongs_to :respondent
belongs_to :question
end
# Comment model
class Comment < ActiveRecord::Base
belongs_to :respondent
belongs_to :question
def self.get_collected_data_by(location)
data = []
respondents = Respondent.completed.find_all_by_office_id(location)
answers = Answer.find_all_by_respondent_id(respondents)
comments = find_all_by_respondent_id(respondents)
respondents.each do |respondent|
hash = {
name: respondent.name,
#...
}
data << hash
end
data
end
end

I am attempting to call Comment.get_collected_data_by() with a specific office. This method's purpose is to aggregate a bunch of data together into an array (data). I need it to create a hash of aggregated data per respondent.

To hopefully make database calls minimal, I am pulling all the data I need in the 3 calls:

  • respondents = Respondent.completed.find_all_by_office_id(location)
  • answers = Answer.find_all_by_respondent_id(respondents)
  • comments = find_all_by_respondent_id(respondents)

I then enumerate through respondents and I need to grab just the answers of that respondent. Is there an easy way to grab them out of the answers variable?

# Respondent model
class Respondent < ActiveRecord::Base
belongs_to :office
has_many :comments
has_many :answers
end
@sankage
Copy link
Author

sankage commented Nov 29, 2011

What I could do is create this:

ans = {}
answers.each do |answer|
  ans[answer.respondent_id] = [] unless ans[answer.respondent_id]
  ans[answer.respondent_id] << answer
end

This would create a hash that I can easily pull answers from given a respondent_id. This doesnt seem like the best way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment