不正确的表单验证

Improper form validation

我 运行 遇到了一个奇怪的问题。这是关于闪光灯的控制器代码:

def create
    user = User.find_by(email: params[:email])
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to root_path, notice: "Signed in!"
    else
        flash.now[:error] = 'Your email or password is incorrect!'
        render "new"
    end
end

关联查看代码如下:

<% if flash.now[:error] %>

        <%= label_tag :email %>
        <%= text_field_tag :email, nil, class: "error"%>

        <%= label_tag :password %>
        <%= password_field_tag :password, nil, class: "error" %>

    <% else %>

        <%= label_tag :email %>
        <%= text_field_tag :email%>

        <%= label_tag :password %>
        <%= password_field_tag :password%>

    <% end %>

错误 class 应导致输入字段变为红色。但是,它们目前会短暂闪烁红色,然后呈现页面。我可以在这里做得更好吗?

谢谢

来自文档:

When you need to pass an object to the current action, you use now, and your object will vanish when the current action is done.

Entries set via now are accessed the same way as standard entries: flash['my-key'].

(见http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-now

尝试删除您视图中的“.now”,改为执行

<% if flash[:error] %>