我幾乎使用了常規腳手架的代碼。唯一的變化是4次塊,我在這個問題上做出4個答案對象。原因是我在視圖中有相應的輸入字段。現在,如果驗證失敗,它會再次呈現new.html.erb,但是在我閱讀它之後不會再次調用「new」動作。但是,我依賴於4.times塊,因爲否則視圖中的循環沒有循環的答案。我該如何解決?我嘗試重定向,但隨後錯誤消息消失了。渲染不運行
新動作
def new
@question = Question.new
4.times do
@question.answers.build
end
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 @question, notice: 'Question 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
嗨,但我有4個輸入字段..並且用戶可能並不總是有4個答案,它可能只有2個,所以如果用戶沒有填寫所有4,那麼不檢查答案文本是否失敗? – LuckyLuke 2012-08-09 12:58:01
我解決了它。我添加了回調,並刪除了拒絕條件。 – LuckyLuke 2012-08-09 13:39:05
很高興它解決了:) – severin 2012-08-10 09:50:40