我有救一個問題,在數據庫中的5個答案,但我不知道我怎麼可以保存答案一種形式,這是我的表格:的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
我應該做些什麼來保存在數據庫中的問題和答案?
謝謝!
行動中,我有它在模型中,但我想念這個問題...對不起! –
我只需要知道我在創建動作中需要寫些什麼...... –
僅僅是一個'@ question.save'應該可以。但要像腳手架一樣處理錯誤。請參閱http://guides.rubyonrails.org/getting_started.html#creating-new-posts – apneadiving