Rails - 无法显示错误消息

时间:2011-10-04 14:46:50

标签: ruby-on-rails notice

当我发送错误的电子邮件时,验证无法通过,但视图中的错误消息不会显示:(

我有模特:

validate :recipient_not_have_invitation, :notice => "That user have already invitation"

def recipient_not_have_invitation
  errors.add :notice, 'That user have already invitation' if InvitationToGroup.find_by_recipient_email_and_group_id(recipient_email, group_id)
end
控制器中的

(...)

if @invitation_to_group.save
  Mailer.invitation_to_group(@invitation_to_group).deliver
  redirect_to root_url, :notice => "Successfully send invitation to user #{@invitation_to_group.recipient_email}"
else
  redirect_to new_invitation_to_group_path(:group_id =>  @invitation_to_group.group_id)
end

在视图中(invitation_to_groups / new.html.erb)

<h2>New Invitation to group </h2>
<% if notice %>
  <p id="notice"><%= notice %></p>
<% end %>

<%= form_for @invitation_to_group do |f| %>
   <% if @invitation_to_group.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@invitation_to_group.errors.count, "error") %> prohibited this user from being invitation:</h2>

      <ul>
      <% @invitation_to_group.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

(...)

1 个答案:

答案 0 :(得分:2)

问题是您在控制器redirect_to之后使用else。所以你要采取新的行动,在这个行动中你有InvitationToGroup.new。因此,您可以无错误地构建新对象;)您需要使用render方法instesd。

PS。你应该考虑使用“formtastic”。它将在视图中改进您的代码。请观看这两个视频广播:http://railscasts.com/episodes/184-formtastic-part-1http://railscasts.com/episodes/185-formtastic-part-2