accepts_nested_attrinutes_for rails3.1rc4

Я использую accepts_nested_attributes_for в модели, но моя дочерняя форма не сохраняется в базе данных?

Я строю вложенную форму почти так же, как в эпизоде ​​196/197 из рельсовых передач Райана Бейтса. У меня есть родительская форма вопроса и в качестве дочерней формы ответа:

модели/вопрос.рб

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

модели/answer.rb

class Answer < ActiveRecord::Base
    belongs_to :question
  belongs_to :user
end

контроллеры/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

просмотры/вопрос/_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» должен позаботиться о его дочерних элементах.

С уважением, Тайс


person Thijs    schedule 17.07.2011    source источник


Ответы (1)


1 Удалите эту строку из контроллера

params[:question][:answers_attributes].keys.each {|key| params[:question][:answers_attributes][key][:user_id] = current_user.id }

2 добавить это в свой вид

<!-- = Nested Answer form = -->
  <div class="answer-field">
    <%= f.fields_for :answers do |builder| %>
      <% builder.object.user = current_user %>
      <%= builder.label :content, "Possible answer" %><br />
      <%= builder.text_field :content, :placeholder => "type an optional answer.." %>
      <%= builder.hidden_field, :user_id %>
    <% end %>
  </div>
<!-- ====================== -->
person fl00r    schedule 17.07.2011
comment
спасибо, но в таблице ответов по-прежнему ничего не сохраняется...? Я действительно не понимаю, почему? - person Thijs; 17.07.2011
comment
Кажется, я уже знаю, что делаю неправильно... глупо, глупо...: accepts_nested_attributes_for :answers, :reject_if =› lambda { |a| a[:text].blank? }, :allow_destroy =› true должно быть: accepts_nested_attributes_for :answers, :reject_if =› lambda { |a| a[:content].blank? }, :allow_destroy =› правда - person Thijs; 17.07.2011