Rails: построение многомодельной формы - PullRequest
0 голосов
/ 06 декабря 2011

У меня есть форма для сохранения вопроса и пять ответов в базе данных, но я не знаю, как мне сохранить ответы, это моя форма:

<%= form_for([:admin, @question]) do |f| %>

...

<%= f.fields_for :answers do |builder| %>
    <%= builder.label :answer, "Risposta", :class => "v-align" %>
    <%= builder.text_field :answer, :rows => 2 %>

    <%= builder.label :correct, "Corretta", :class => "v-align" %>
    <%= builder.check_box :correct %>
<% end %>

...

<% end %>

Мои модели:

class Question < ActiveRecord::Base
    has_many :answers
    accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
    attr_accessible :answers_attributes, :quiz_id, :question, :sort_order, :point_value, :number_correct, :explanation
end

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

И мой контроллер "Вопрос":

def new
    @question = Question.new
    5.times { @question.answers.build }

    respond_to do |format|
        format.html # new.html.erb
        format.json { render :json => @question }
    end
end

def create
    @question = Question.new(params[:question])

    respond_to do |format|
        if @question.save
            format.html { redirect_to admin_question_path(@question), :notice => 'Test was successfully created.' }
            format.json { render :json => @question, :status => :created, :location => @question }
        else
            format.html { render :action => "new" }
            format.json { render :json => @question.errors, :status => :unprocessable_entity }
        end
    end  
end

Что мне нужно сделать, чтобы сохранить вопрос и ответ в базе данных?

Спасибо !!

Ответы [ 2 ]

3 голосов
/ 06 декабря 2011

В модели Question вы пропускаете только accepts_nested_attributes_for :answers.

См. Документ .

EDIT:

Вы должны добавить answers_attributes в список attr_accessible

1 голос
/ 06 декабря 2011

Вам стоит взглянуть на два RailsCasts:

http://railscasts.com/episodes/196-nested-model-form-part-1 и http://railscasts.com/episodes/197-nested-model-form-part-2

Они могут вам очень помочь!

Человек, стоящий заэти броски, Райан Бейтс, создали великолепный драгоценный камень для обработки вложенных форм!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...