ruby-on-rails – rails update_attributes在尝试更新db值时返回false

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – rails update_attributes在尝试更新db值时返回false前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
希望有人能指向我正确的方向.

我有一个控制器Update def运行“update_attributes”.目前它返回false,没有错误消息.我对Ruby很新,但不是编码,而且这让我感到好几天!我试图使用下面指定的值来获取用户模型和数据库更新.

def update   
    #get currently logged in user
    @user = current_user
    #update user params based on edit form...
    if @user.update_attributes(params[:user])
        redirect_to profile_path,:notice  => "Successfully updated profile."
    else
        render :action => 'edit'
    end
end

我的编辑def ….

def edit
    @user = current_user
end

表单发送以下更新方法

--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
utf8: ✓
_method: put
authenticity_token: 9T4ihVI0p8j7pZEFxof3Bfahi2a+o3BPmtXJDnfHT4o=
user: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
  first_name: Amanda
  last_name: Ross
  is_owner: '1'
  email: example@googlemail.com
commit: Update
action: update
controller: users
id: '20'

而params [:user]返回:

{"first_name"=>"Amanda","last_name"=>"Ross","is_owner"=>"1","email"=>"example@googlemail.com"}

所有这些字段都在型号的attr_accessible中,我可以创建一个用户没有任何问题.

这里的development.log输出(对不起,有点凌乱)….

Started PUT "/users/20" for 127.0.0.1 at 2012-04-17 10:39:29 +0100
Processing by UsersController#update as HTML
  Parameters: {"utf8"=>"✓","authenticity_token"=>"9T4ihVI0p8j7pZEFxof3Bfahi2a+o3BPmtXJDnfHT4o=","user"=>    {"first_name"=>"Amanda","email"=>"example@googlemail.com"},"commit"=>"Update","id"=>"20"}
  [1m[36mUser Load (1.0ms)[0m  [1mSELECT "users".* FROM "users" WHERE "users"."id" = 20 LIMIT 1[0m
>>>>>>>>>>>>
{"first_name"=>"Amanda","email"=>"example@googlemail.com"}
     [1m[35m (0.0ms)[0m  begin transaction
     [1m[36mUser Exists (0.0ms)[0m  [1mSELECT 1 FROM "users" WHERE (LOWER("users"."email") =     LOWER('example@googlemail.com') AND "users"."id" != 20) LIMIT 1[0m
  [1m[35mUser Exists (0.0ms)[0m  SELECT 1 FROM "users" WHERE ("users"."email" = 'example@googlemail.com'     AND "users"."id" != 20) LIMIT 1
  [1m[36m (0.0ms)[0m  [1mrollback transaction[0m
 Rendered users/_form.html.erb (7.0ms)
 Rendered users/edit.html.erb within layouts/application (10.0ms)
 Rendered layouts/_includes.html.erb (30.0ms)

有人可能有帮助指出我要错了吗?

提前致谢!

解决方法

#update_attributes和#save将首先检查您的模型实例是否#valid?然后继续写入数据库.如果您的模型实例不是#valid?,那么这些方法将返回false.看看你的模型实例有什么问题,看看你的模型的#errors.
Rails.logger.info(@user.errors.messages.inspect)

或者,嵌入您的方法,

def update   
  @user = current_user
  if @user.update_attributes(params[:user])
    redirect_to profile_path,:notice  => "Successfully updated profile."
  else
    # print the errors to the development log
    Rails.logger.info(@user.errors.messages.inspect)
    render :action => 'edit'
  end
end

猜你在找的Ruby相关文章