0

account_settings我在控制器中有一个表单,它user通过users_controller. 错误消息没有通过。下面看一下代码。

account_settings/account.html.haml

= form_for @user, :url => { :controller => "users", :action => "update", :id => @user.id } do |f|
  - if @user.errors.any?
    .alert.alert-error
      %h4
        Please address the following errors:
      %ul
        - @user.errors.full_messages.each do |msg|
          %li= msg
  form stuff...

account_settings_controller

def account
  @user = current_user
end

users_controller

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user])
    flash[:notice] = "User was successfully updated."
  end
  redirect_to :back
end

表单不会更新,但不会传回错误消息。有什么想法吗?

4

1 回答 1

1

发生这种情况是因为您正在返回重定向。该@user对象不会在重定向中持续存在。您应该执行以下操作:

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user])
    flash[:notice] = "User was successfully updated."
    redirect_to :back
  else
    render :edit
  end
end

在这里,我们在更新成功时重定向,但如果没有,我们渲染edit动作。因此我们可以访问@user,并且您的错误将出现在@user.errors

于 2012-05-04T18:16:58.383 回答