2011-09-28 4 views
1

헉. 그것은 나를 데려오고있어. 내 컨트롤러에서Rails 뷰 템플릿에서이 불쾌한 쿼리를 제거하려면 어떻게해야합니까?

:

@assessor = Assessor.find(params[:id]) 
@assessor.answers.build if @assessor.answers.empty? 

내보기에서 :

= simple_form_for @assessor do |f| 
    - @assessor.candidates.each do |candidate| 
     - @assessor.assessment_competencies.each do |competency|      

      - if @assessor.answers.all?{|a| a.new_record?} 
       - competency.behaviors.each do |behavior| 
        = f.fields_for :answers do |f| 
         - @assessor.standard_answer_choices.each do |choice| 
          = f.input :assessor_id, :as => :hidden, :input_html => {:value => @assessor.id} 
          = f.input :candidate_id, :as => :hidden, :input_html => {:value => candidate.id} 
          = f.input :behavior_id, :as => :hidden, :input_html => {:value => behavior.id} 
          = f.input :competency_id, :as => :hidden, :input_html => {:value => competency.id} 
          = f.association :answer_choice, :collection => [choice], :as => :radio 

      - else 
       - competency.behaviors.each do |behavior| 
        - answer = Answer.find_or_create_by_behavior_id_and_assessor_id_and_candidate_id(behavior.id, @assessor.id, candidate.id) 
        = f.fields_for :answers, answer do |f| 
         = f.input :assessor_id, :as => :hidden, :input_html => {:value => @assessor.id} 
         = f.input :candidate_id, :as => :hidden, :input_html => {:value => candidate.id} 
         = f.input :behavior_id, :as => :hidden, :input_html => {:value => behavior.id} 
         = f.input :competency_id, :as => :hidden, :input_html => {:value => competency.id} 
         = f.association :answer_choice, :collection => [choice], :as => :radio 

답변

1

웁은, 그건 밥맛이다. 당신은 당신이 깨질 수 원한다면

= simple_form_for @assessor do |f| 
    - @assessor.candidates.each do |candidate| 
    - @assessor.assessment_competencies.each do |competency|      

     - if @assessor.answers.all?{|a| a.new_record?} 
     - competency.behaviors.each do |behavior| 
      = answers_fields f, candidate, behavior, competency 

     - else 
     - competency.behaviors.each do |behavior| 
      - answer = @assessor.answers.find_or_create_by_behavior_id_and_candidate_id behavior, candidate 

      = answers_fields f, candidate, behavior, competency, answer 

: 즉,이 아래로보기를 잘라 것

module AssessorsHelper 
    def answers_fields f, candidate, behavior, competency, answer=nil 
    assessor = f.object 

    f.fields_for :answers, answer do |f| 
     f.hidden_field :assessor_id, :value => assessor.id 
     f.hidden_field :candidate_id, :value => candidate.id 
     f.hidden_field :behavior_id, :value => behavior.id 
     f.hidden_field :competency_id, :value => competency.id 
     f.association :answer_choice, :collection => [choice], :as => :radio 
    end 
    end 
end 

: 도우미로 fields_for 블록 밖으로 반복 당신이 꺼낼 수있는 최소한

그것은 각 안쪽 루프를위한 도우미로 내려갔습니다. 그러나 당신은 아이디어를 얻었습니다.

+0

고마워요, 요르단. 내 예쁘지는 않지만 내 질문의 표현을 단순화하기 위해 부분 코드를 제거했습니다. 나는 부분적인 것 대신 도우미의 사용을 좋아한다! – Blastula

관련 문제