我通常只使用flash[:notice]发送通知消息,例如“您的帐户已成功更新”,或者flash[:error]或
error_msg_for
错误信息。对于验证失败导致的错误,我使用error_msg_;对于所有其他类型的错误消息,使用flash[:error]。除非绝对必要,否则我注意不要让他们两个都采取相同的行动。
我还试图避免将使用返回到他们刚提交的表单,如果他们的操作成功。我认为这是在发送矛盾的信号来发布一条成功消息,并将用户发送回他们刚提交的表单。我的经验法则是“成功时重定向,失败时呈现”。
redirect to @user
如果@user保存在更新中,但如果保存失败将呈现:edit。
样本控制器代码。
before_filter :identify_user, :except => :index
def update
@user = User.find(params[:id])
if @user.update_attributes(params)
flash[:notice] = "Your account was updated successfully"
redirect_to @user
else
render :action => :edit
end
end
def index
end
def identify_user
begin
@user = User.find(params[:id])
rescue
flash[:error] = "You specified an unknown user"
redirect users_path
end
end
我的通知部分调用了我的应用程序布局。
<div id="notification_area">
<% flash.each do |key, value| %>
<% if value %>
<div id="<%=key%>">
<%= value %>
</div>
<%end%>
<%end%>
</div>