rails update_attributes在尝试更新db值时返回false

时间:2012-04-17 10:04:51

标签: ruby-on-rails ruby ruby-on-rails-3 controller update-attributes

希望有人能指出我正确的方向。

我有一个控制器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", "last_name"=>"Ross", "is_owner"=>"1", "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", "last_name"=>"Ross", "is_owner"=>"1", "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)

有人可能帮忙指出我哪里出错了吗?

提前致谢!

2 个答案:

答案 0 :(得分:45)

在继续写入数据库之前,#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

答案 1 :(得分:7)

通过调用factory = { "make_person" => lambda { Person.new } } factory["make_person"].call 来更新属性时,您也可以获得更好的内省,这会引发异常,而不仅仅是返回false。