質問と回答のモデルの間にネストされたリソースを構築しました。これは私が質問を作成するために使用したフォームです。関連する情報をラップするだけです。
<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
、レールの方法または私の表示フォームのためですか?