I'm building a quizz application in which the user can enter the correct answer into a number field. I want to use the value in this field as a parameter in the button_to method to create a new answer. If i click the button, it does create a new answer with the first two parameters as attributes, but the attribute for givenanswer is empty. I don't get an error, it just doesn't set my givenanswer parameter as an attribute.
How do i get a value in a field and use it as a parameter? Should i use a helper? (i'm new to rails and haven't made use of helpers yet).
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
UPDATE: I tried to use it in a form and it seemed to work: now i do have an attribute givenanswer for Answer objects. however, it always stores a 0, whatever number I insert in the form.
<%= 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 %>