我在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