我正在构建一个quizz应用程序,用户可以在其中输入正确的答案到数字字段。我想使用此字段中的值作为button_to方法中的参数来创建新答案。如果我单击该按钮,它会创建一个新的答案,前两个参数作为属性,但givenanswer的属性为空。我没有收到错误,它只是没有将我的givenanswer参数设置为属性。
如何在字段中获取值并将其用作参数?我应该使用帮手吗? (我刚刚开始使用铁杆,还没有使用帮手)。
Questionscontroller
class QuestionsController < ApplicationController
def showquestion
@question = Question.find(params[:id])
end
# . . .
showquestion
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] } %>
Answercontroller
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答案对象。 但是,它总是存储一个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 %>
答案 0 :(得分:0)
我认为您应该使用表单,但如果您真的想要,可以使用javascript动态更改值