7

在我的应用程序中,我有时会即时创建用户,并且用户的电子邮件必须是有效格式并且是唯一的。

我想根据哪个验证导致错误被重定向到不同的地方:格式无效与重复。

在我的代码中,我有

    begin
      user.save!
      flash[:notice] = "Created new user #{email} with password #{password}"

    rescue ActiveRecord::RecordInvalid => e
      flash[:alert] = "Failed to create account because #{e.message}"
      redirect_to SOMEPLACE
    end

如果电子邮件格式无效(例如“user@example”) e.message 为“验证失败:电子邮件无效”

如果电子邮件已经存在于表中,e.message 为“验证失败:电子邮件已被占用”

我讨厌解析 e.message 文本以确定原因的想法......救援处理程序是否有更好的方法来检测引发 ActiveRecord::RecordInvalid 异常的根本原因?

PS我知道在这个例子中我可以在保存之前简单地检查已经存在的电子邮件,但我试图了解检测和处理不同验证失败并抛出相同异常的一般解决方案。

4

2 回答 2

1

执行此操作的标准 Rails 方法不是使用引发异常的 bang 运算符,而是使用标准 save 方法并检查它是否返回 true 或 false:

if @user.save
  flash[:notice] = "User created."
  redirect_to :action => :index
else
  flash[:alert] = "User could not be created."
  render :action => :new
end

在您的用户创建视图中:

<% if @user.errors.any? %>
  <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
  </ul>
<% end %>
于 2012-03-06T21:47:58.613 回答
0

如果我理解您正在尝试正确执行的操作,那么一种方法就是断言字段级别存在错误。例如

if user.errors[:field_name].present?
  redirect_to path_for_field_name_error
end

或者,您定义一些将哪些字段重定向到哪里的映射作为常量(例如REDIRECT_PATHS,在这种情况下,您最终会得到类似的内容:

redirect_to REDIRECT_PATHS[field_name] if user.errors[:field_name].present?

您可以在其中循环遍历field_names.

于 2014-03-17T21:52:06.513 回答