开发者

Rails - error messages can't be displayed

When I send wrong email, validation can't pass but error messages in views don't be displayed :(

I have in models:

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

in controller:

(...)

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

In views (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开发者_如何学Go.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 %>

(...)


The problem is that you are using redirect_to after else in your controller. So you are going to new action and in this action you have InvitationToGroup.new. So you build new object without errors ;) You need to use render method instesd.

PS. you should really consider using "formtastic". It will imporve your code in views. Please watch this two railscasts: http://railscasts.com/episodes/184-formtastic-part-1 and http://railscasts.com/episodes/185-formtastic-part-2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜