2015-09-20 109 views
1

我正在驗證我正在構建的遊戲應用程序的答案。我遇到了正確的數據庫調用問題。驗證答案

問題#validate_answer

def validate_answer 
    @answer = Answer.where(correct: true) 
    @correct_answer = @answer 
    @selected_answer = params[:answer] 

    #check if the submitted answer is the correct answer 

    if @selected_answer == @correct_answer 
    render :success 
    else 
    render :error 
    end 
end 

Question.rb

class Question < ActiveRecord::Base 
    belongs_to :category 

    has_many :answers 

    has_one :video_clue 
    has_many :answers 

    def correct_answer 
    answers.find_by correct: true 
    end 
end 

Answer.haml

%form#form{:action => results_path(@question), :method => "post"} 

- @answers.each do |answer| 

.form-group 
.radio 

%input{:name => 'q_id', :type => 'hidden',:value =>'#{@question.id}'} 

%input.btn.btn-default.btn-block{:name => 'answer', :style => 'vertical-align: middle; margin:0px;', :type => 'submit', :value => answer.text} 

Seeds.rb

q = Question.create question: "In what year did MTV (Music Television) premiere and what was the first music video the channel aired?", category_id: 1 
q.answers.create text: '1982 Michael Jackson Bille Jean' 
q.answers.create text: '1984 Madonna Like a virgin' 
q.answers.create text: '1981 The Buggles Video Killed The Radio Star', correct: true 

目標是將所選答案與正確答案進行匹配。它不斷呈現'失敗'頁面。

+0

你能回答得問題?你必須首先在'validate_answer'中確定你的問題。如果你可以得到這個問題,你可以在'def validate_answer'中更改你的'@answer = @ question.correct_answer' – akbarbin

+0

我已經試過並且沒有工作 –

回答

0

我相信你正在比較一個字符串到一個ActiveRecord對象當然會失敗。

'1982 Michael Jackson Bille Jean' != <Answer id:1 text:"1982 Michael Jackson Bille Jean">

你有沒有考慮傳遞答案的ID而不是文本,然後進行比較。這將允許您查詢用戶選擇的答案。例如

問題#validate_answer

def validate_answer 
    @answer = Answer.where(correct: true) 
    @correct_answer = @answer 
    @selected_answer = Answer.find(params[:answer_id]) 

#check if the submitted answer is the correct answer 

    if @selected_answer == @correct_answer 
    render :success 
    else 
    render :error 
    end 
end 

或者你需要比較params[:answer]於文本屬性

問題#validate_answer

def validate_answer 
    @answer = Answer.where(correct: true) 
    @correct_answer = @answer.text 
    @selected_answer = params[:answer] 

#check if the submitted answer is the correct answer 

    if @selected_answer == @correct_answer 
    render :success 
    else 
    render :error 
    end 
end 
+0

沒有運氣。我沒有answer_id的params。當用戶選擇一個答案時,它被認爲是被認可的,所以這就是爲什麼我使用params [:answer]。 –

+0

不知道我明白你來自哪裏,但我更新了備用。你總是可以從答案中提取文本值。但是,如果你做的Answer.where(正確:真)不會提出所有正確的答案,不管問題是什麼? – pyRabbit

+0

確實如此,但不幸的是,當我執行@ answer.text時,出現錯誤,但是@answer [0] .text將適用於第一個。 –