我在Rails上構建了一個應用程序,用戶創建一個Test,轉到該測試的顯示視圖並填充一個帶有問題答案的窗體。如果問題的答案與「correct_answer」(在控制器中定義)相匹配,則會出現閃回消息,表明答案正確,並且會出現一個繼續到root_path的按鈕。如果答案錯誤,閃光燈會顯示「錯誤的答案」。Rails flash消息
我的問題是,即使沒有給出答案,Flash消息也會說錯的答案。我只希望該消息在用戶提交表單後出現。我明白爲什麼會發生這種情況,我只是不確定如何解決這個問題。下面是一個測試顯示視圖:
<div class="col-md-8 col-md-push-2">
<h4>Current Score: <%= @test.score %></h4>
<br /><br />
<div class="form_group">
<%= form_tag test_path(@test), :method=> 'get' do %>
<h4>What is my first name?</h4>
<div class="form-group">
<%= text_field_tag :answer, params[:answer], class: 'form-control' %>
</div>
<% if !flash[:success] %>
<div class="form-group">
<%= submit_tag "Submit", class: "btn btn-primary" %>
</div>
<% end %>
<% end %>
</div>
<% if flash[:success] %>
<%= link_to "Continue", root_path, class: "btn btn-success pull-right" %>
<% end %>
</div>
下面是測試控制器,它包含違規show動作:
class TestsController < ApplicationController
def index
@test = Test.new
@tests = Test.all
end
def show
@test = Test.find(params[:id])
correct_answer = "jack"
user_answer = params[:answer]
if user_answer == correct_answer
flash.now[:success] = "That is correct!"
new_score = @test.score += 1
@test.update(score: new_score)
elsif params[:answer] != correct_answer
flash.now[:danger] = "Wrong answer"
end
end
def create
@test = Test.create(test_params)
if @test.save
redirect_to test_path(@test)
flash[:success] = "Test created"
else
flash[:danger] = "There was a problem"
render "index"
end
end
def destroy
@test = Test.find(params[:id])
if @test.destroy
flash[:success] = "Your test was removed"
redirect_to root_path
end
end
private
def test_params
params.require(:test).permit(:score, :user_id)
end
end
有沒有更好的方式來做到這一點?如果沒有,我可以以某種方式阻止閃存消息出現在初始加載?我只希望它在表單提交後出現。提前致謝。
'params [:answer]'只有在您提交表單時纔可用? – Pavan
你也可以使用在初始加載時在服務器中生成的'params'來更新問題嗎? – Pavan