Я использую acceptpts_nested_attributes_for в модели, но моя дочерняя форма не сохранена в базе данных?
Я создаю вложенную форму почти так же, как в эпизоде 196/197 из Ryan Bates railscasts.У меня есть форма родительского вопроса, а в детстве форма ответа:
models / question.rb
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? },
:allow_destroy => true
validates :content, :presence => true
end
models / answer.rb
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
end
controllers /questions_controller.rb
class QuestionsController < ApplicationController
before_filter :authenticate_user!
def index
setup_questions
end
def create
@question = Question.new(params[:question])
#this is to get every id_key from the user into the params of the answer
params[:question][:answers_attributes].keys.each {|key| params[:question][:answers_attributes][key][:user_id] = current_user.id }
@question.user_id = current_user.id
if @question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
def edit
@question = Question.find(params[:id])
end
def update
@question = Question.find(params[:id])
respond_to do |format|
if @question.update_attributes(params[:question])
format.html { redirect_to(@question, :notice => 'Question was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @question.errors, :status => :unprocessable_entity }
end
end
end
def show
@question = Question.find(params[:id])
end
def destroy
@question = Question.find(params[:id])
#authorize! :destroy, @question
@question.destroy
redirect_to questions_path, :notice => "Successfully deleted question: #{@question.content}."
end
private
def setup_questions
@questions = Question.all
@question ||= Question.new
@question.answers.build #to build the answers form
end
end
views / question / _form.html.erb
<%= form_for(@question) do |f| %>
<!-- =================== -->
<!-- = Error handeling = -->
<% if @question.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% @question.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<!-- =================== -->
<!-- ================= -->
<!-- = Question form = -->
<div class="field">
<%= f.label :content, "Question" %><br />
<%= f.text_field :content, :placeholder => "type your question here.." %>
</div>
<!-- ====================== -->
<!-- = Nested Answer form = -->
<div class="answer-field">
<%= f.fields_for :answers do |builder| %>
<%= builder.label :content, "Possible answer" %><br />
<%= builder.text_field :content, :placeholder => "type an optional answer.." %>
<% end %>
</div>
<!-- ====================== -->
<div class="actions">
<%= f.submit %>
</div>
<!-- ================= -->
<% end %>
Так что теперь главный вопрос ... Почему он ничего не сохраняет из поля ответа вбаза данных?Я подумал, что одного действия создания у родителя (вопроса) должно быть достаточно, и что "accepts_nested_attributes_for" должен позаботиться о его потомке (ах).
С уважением, Thijs