我正在构建一个quizz应用程序,用户可以在其中的数字字段中输入正确答案。我想使用这个字段中的值作为button_to方法中的参数来创建一个新的答案。如果我点击按钮,它会创建一个新的答案,其中前两个参数是属性,但givenanswer的属性是空的。我没有得到错误,只是没有将我的givenanswer参数设置为属性。
如何获取字段中的值并将其用作参数?我应该找个帮手吗?(我刚接触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
更新:我试着在一个表单中使用它,它似乎起了作用:现在我为Answer对象提供了一个属性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 %>
我认为你应该使用一个表单来实现这一点,但如果你真的想,你可以使用javascript 动态更改值