Skip to content

Instantly share code, notes, and snippets.

@sankage
Created November 29, 2011 02:26
Show Gist options
  • Select an option

  • Save sankage/1403091 to your computer and use it in GitHub Desktop.

Select an option

Save sankage/1403091 to your computer and use it in GitHub Desktop.
Collection Sub-Selection
# Answer model
class Answer < ActiveRecord::Base
belongs_to :respondent
belongs_to :question
end

I am pulling all respondents for an office. With each respondent I need to pull out an answer to a specific question. How can I do that?

respondent.answers is an array of answers, how do I grab only the member that has a certain question_id?

data = []
respondents = Respondent.completed.includes([:office, :answers]).find_all_by_office_id(office)
    
respondents.each do |respondent|
  hash = { 
    office:     respondent.office.name,
    name:       respondent.name, 
    #nps_value:  respondent.answers ...,
  }
      
  data << hash
end
# Respondent model
class Respondent < ActiveRecord::Base
belongs_to :office
has_many :answers
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment