0

私は rails/RhoMobile に少し慣れていないので、子オブジェクトを親オブジェクトに追加して、フォームのインスタンス変数 @questions のメンバーとして使用できるようにする方法がわかりません。これが私のコントローラーメソッドです

def diary_day_one_morning
  qgroup = "activity_day_one_morning"
   @questions = Question.find(:all, :conditions => { { :name => "qgroup", :op => '=' } => qgroup } )
  # make sure all questions have an answer
  @questions.each do |q|
    a = Answer.find(:all, :conditions => { { :name => "question_id", :op => '=' } => q.object }).first
    if not a
      a = Answer.new
      a.question_id = q.object
      a.save
    end
    #@questions[q].answer = a # here is my issue!!!
  end
  render :action => :diary_day_one_morning, :back => url_for(:action => :index)
end

@questions[q].answer の部分で、質問を回答に結合する方法について少し迷っています。次に、フォームで回答を参照するにはどうすればよいですか? これが私がすでに持っているものです:

    <% @questions.each_with_index do |question, qcount| %>
      <div class="ui-block-a">
        <div class="ui-bar ui-bar-e">
          <%= question.qpromptshort %>
        </div>
      </div>
      <% a = Answer.find(:all, :conditions => { { :name => "question_id", :op => '=' } => question.object }).first %>

      <% if a %>
        <input type="hidden" id="answer<%=qcount%>[object]" name="answer<%=qcount%>[object]" value="<%=a.object%>" />
        <div class="ui-block-b">
            <input type="text" id="answer<%=qcount%>[value1]" name="answer<%=qcount%>[value1]" value="<%=a.value1%>" />
        </div>
   .......

回答 (a) を参照するのではなく、質問のメンバーとして参照することをお勧めします。

4

1 に答える 1

0

each_with_indexメソッドを使用して、@questions配列内の各オブジェクトのインデックスを取得できます。

 @questions.each_with_index do |q,qindex|
    a = Answer.find(:all, :conditions => { { :name => "question_id", :op => '=' } => q.object }).first
    if not a
      a = Answer.new
      a.question_id = q.object
      a.save
    end
    # use qindex to add it back into the @questions array
    @questions[qindex].answer = a 
  end

次に、ページで回答がquestion.answerとして利用可能になります。

于 2012-05-13T13:01:44.893 に答える