微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/272639.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐