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 回答