Rails:构建多模型表单

时间:2011-12-05 22:30:29

标签: ruby-on-rails

我有一个表格可以在数据库中保存一个问题和五个答案,但我不知道如何保存答案,这是我的表格:

<%= 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 个答案:

答案 0 :(得分:3)

您只能错过accepts_nested_attributes_for :answers模型中的Question

See doc

编辑:

您应该将answers_attributes添加到attr_accessible列表

答案 1 :(得分:1)

你应该看看两个RailsCasts:

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

他们可能会帮到你很多!

这些演员背后的男人Ryan Bates创造了一个伟大的宝石来处理嵌套形式!