0

我正在为我的应用程序设置基本身份验证/登录,并遇到了一个烦人的小问题。

下面是我的“创建”方法:

def create
    @user = User.new(user_params)

    if @user.save
      flash[:notice] = "You signed up successfully"
      flash[:color]= "valid"
    else
      flash[:notice] = "Form is invalid"
      flash[:color]= "invalid"
    end

    render "index"
end

在渲染索引时有时会得到表单无效,有时你已经注册成功,即使数据成功添加到数据库,我也会得到表单无效。

<% if flash[:notice] %>
<div class="notice"><%= flash[:notice] %></div>
4

2 回答 2

0

原因是您使用render而不是redirect_to.

flash是存储在会话中的东西,只会在下一个请求时生效。

在您的控制器中,只有一个请求,闪存仍然是会话中存储的一些旧信息,render不会更新它。

要修复,请替换renderredirect_to

于 2013-09-14T07:20:41.150 回答
0

有两件事。

首先看看如何flash工作。如果你放了一些东西,它会一直留在那里,直到下一个请求完成。

flash[:foo] = 'bar'
flash[:foo] #=> 'bar' 

# redirect the user or reload of the page
flash[:foo] #=> 'bar' 

# redirect the user or reload of the page
flash[:foo] #=> nil

对于应该在同一个请求中显示但不在下一个请求中显示的错误消息,请调用now

flash.now[:foo] = 'bar'
flash[:foo] #=> 'bar' 

# redirect the user or reload of the page
flash[:foo] #=> nil

进一步阅读:http ://edgeguides.rubyonrails.org/action_controller_overview.html#the-flash

另一件事:如果您不只是处理数据的获取请求(而是创建、更新、删除),请在该操作成功后重定向用户。不只是渲染另一个视图。原因是如果用户重新加载页面,浏览器将重新发送它的最后一个请求。并且 - 在您的情况下 - 尝试使用相同的数据创建第二个用户。

tldr:如果save不成功,render则再次表单。如果save成功,redirect用户 toshowindex

于 2013-09-14T07:35:20.283 回答