2010-02-07 2 views

답변

2

그 SurveySection has_many :questions를 가정하면, 당신은이를 단순화 할 수 있습니다 :

sections.map(&:questions).flatten 

또는 메소드가 액티브 모델에 정의되어있는 경우, 당신이 has_many :questions, :through => :sections하고 메소드를 정의 할 필요가 없습니다 선언 단지 수

조금도. 눈에 블록없이

+0

inject'에 대한 감사합니다! 그게 내가 찾고 있던 바로 그거야, 지금 당장 말이야. –

2
def questions 
    sections.map do |section| 
    Question.find_all_by_survey_section_id(section.id) 
    end.flatten 
end 

또는

def questions 
    sections.inject([]) do |all, section| 
    all.concat Question.find_all_by_survey_section_id(section.id) 
    end 
end 
+0

한' – molf

0
당신은지도를 사용하거나 내가 방금 전화하지 않기 때문에 이것에 대한 발동하는 기호를 사용할 수있는 것 같아요,하지만 너무

def questions 
    sections.map{|section| Question.find_all_by_survey_section_id(section.id)}.flatten 
end 

처럼, 수집 할 수 있습니다

콜렉션의 메소드

0

:

def questions 
    sections.map(&:id).flat_map(&Question.method(:find_all_by_survey_section_id)) 
end 
관련 문제