我正在构建一个测验应用程序,用户可以在其中将正确答案输入数字字段。我想将此字段中的值用作 button_to 方法中的参数来创建新答案。如果我单击该按钮,它确实会创建一个新答案,其中前两个参数作为属性,但给定答案的属性为空。我没有收到错误,只是没有将我的给定答案参数设置为属性。
如何获取字段中的值并将其用作参数?我应该使用助手吗?(我是 Rails 新手,还没有使用过助手)。
问题控制器
class QuestionsController < ApplicationController
def showquestion
@question = Question.find(params[:id])
end
# . . .
显示问题
views/questions/showquestion/1
<b>Question:</b>
<%=h @question.word %>
<b>1:</b>
<%=h @question.ans1 %>
<b>2:</b>
<%=h @question.ans2 %>
<b>The correct answer is number: </b>
<%=number_field :givenanswer, params[:givenanswer]%>
<%= button_to 'add answer', {:controller => "answers", :action => "create",
:question_id => @question.id, :questionfinished => Time.now, :givenanswer => params[:givenanswer] } %>
应答控制器
class AnswersController < ApplicationController
before_action :set_answer, only: [:show, :edit, :update, :destroy]
# POST /answers
# POST /answers.json
def create
question =Question.find(params[:question_id])
questionfinished = params[:questionfinished]
givenanswer = params[:givenanswer]
@answer = Answer.new(question: question, questionfinished: questionfinished, givenanswer: givenanswer)
respond_to do |format|
if @answer.save
format.html { redirect_to @answer, notice: 'Answer was successfully created.' }
format.json { render action: 'show', status: :created, location: @answer }
else
format.html { render action: 'new' }
format.json { render json: @answer.errors, status: :unprocessable_entity }
end
end
end
更新:我尝试以一种形式使用它,它似乎有效:现在我确实有一个属性 givenanswer 用于 Answer 对象。但是,它总是存储一个 0,无论我在表单中插入什么数字。
<%= form_tag(:controller => "answers", :action => "create", :question_id => @question.id, :questionfinished => Time.now, :givenanswer => :givenanswer) do %>
<p>
<b>Het juiste antwoord is nummer: </b>
<%=number_field :givenanswer, params[:givenanswer]%>
</p>
<p><%= submit_tag("voegantwoordtoemetformtag")%></P>
<% end %>