0

質問と回答のモデルの間にネストされたリソースを構築しました。これは私が質問を作成するために使用したフォームです。関連する情報をラップするだけです。

<fieldset>
  <legend>Question</legend>
    <%= render 'new_question_fields', question_form: question_form %>

  <legend>Answer</legend>
    <%= question_form.simple_fields_for :answers do |answer_form| %>
      <%= render 'answer', f: answer_form %>
    <% end %>
</fieldset>

これは私のanswer部分です:

<div class="answer_fields well fields">
  <%= f.input :correct, label: 'This answer is correct.' %>
  <%= f.input :content, input_html: { rows: 3, class: 'span6' } %>
</div>

これは私のインデックスページです。質問を表示します。

<ul class="questions">
  <% @questions.each do |question| %>
    <li><%= question.content %></li>
    <ol class="answers">
      <% question.answers.each do |answer| %>
        <li><%= answer.content %></li>
     <% end %>  
    </ol>
  <% end %>
</ul>

新しい質問を作成するページで、4つの質問の回答に対して4つのフィールドを作成しました。これは、htmlでレンダリングされたときの4つのtextareaのhtmlコードです。

<textarea cols="40" id="question_answers_attributes_0_content" name="question[answers_attributes][0][content]" rows="3"></textarea>
<textarea cols="40" id="question_answers_attributes_1_content" name="question[answers_attributes][1][content]" rows="3"></textarea>
<textarea cols="40" id="question_answers_attributes_2_content" name="question[answers_attributes][2][content]" rows="3"></textarea>
<textarea cols="40" id="question_answers_attributes_3_content" name="question[answers_attributes][3][content]" rows="3"></textarea>

たとえば、フィールドの順序は0、1、2、3ですが、質問を保存すると、回答の順序が逆になります。例:

A,B,C,Dフォーム上のtextareaの順序に対応する4つの回答を入力する0,1,2,3と、質問が保存されると、次のように表示されます。 D,C,B,A、最初にtextareaの値を保存しquestion[answers_attributes][3][content]、次にquestion[answers_attributes][2][content]...

更新:これは私のインデックスであり、質問コントローラーでアクションを作成します:

def index
  @questions = Question.where("user_id = ?", current_user.id).paginate(page: params[:page], per_page: 10)
end

def create
  @question = Question.new(params[:question])
  @question.question_type_id = params[:question_type_id]
  @question.user_id = current_user.id

  if @question.save
    flash[:success] = "Successfully created question."
    redirect_to questions_url
  else
    render 'new'
  end
end

私のanswerモデル:

class Answer < ActiveRecord::Base
  attr_accessible :content, :question_id, :correct
  belongs_to :question
end

質問が保存されるとどうなりますか?これはsave、レールの方法または私の表示フォームのためですか?

4

1 に答える 1

0
  • question.answers.order("created_at ASC")...また;
  • question.answers.order("created_at DESC")...

そのうちの1つは逆の順序にする必要があります。

-

しかし、そのトピックについてはもっと詳しく-スタックがそこでどのように処理されるかについてだと思います。あなたはその作成中に質問の属性としてそれを渡すことによってそれぞれの答えを作成しています、そしてそれはおそらくミックスです。Railsとlog_level付き:debugのデータベースからのログは、それがデータベースにどのように入るかを確認するのに役立つはずです。

またid ASC、IDは時間とともに増加し、それは-とまったく同じであるため、おそらく機能しますが、created_at ASCIDがランダムである場合があるため、IDに依存することが常に適切なアプローチであるとは限りません。

于 2012-11-09T20:06:19.640 に答える