ruby-on-rails – Model / ActiveRecord不保存新数据
发布时间:2020-12-17 02:04:23 所属栏目:百科 来源:网络整理
导读:我已经确认这种方法有效.基本上它从控制器接收电子邮件并更改特定用户的电子邮件. 但是它实际上从未保存过数据.我传递了错误的电子邮件格式,如果我传递正确的电子邮件方法返回true,则返回false,这意味着它分配了一封新电子邮件并称为安全. # Allows user to
我已经确认这种方法有效.基本上它从控制器接收电子邮件并更改特定用户的电子邮件.
但是它实际上从未保存过数据.我传递了错误的电子邮件格式,如果我传递正确的电子邮件方法返回true,则返回false,这意味着它分配了一封新电子邮件并称为安全. # Allows user to change email address def change_email(newmail) address = EmailVeracity::Address.new(newmail) if address.valid? self.email = newmail self.save return true else return false end end 我首先检查了日志中的任何提示,但我得到的只是: Started POST "/members/editmail" for 127.0.0.1 at 2013-04-25 17:33:44 +0200 Processing by MembersController#editmail as HTML Parameters: {"authenticity_token"=>"*****=","mail"=>"*****@gmail.com"} ←[1m←[35mUser Load (1.0ms)←[0m SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1 ←[1m←[36mCharacter Load (0.0ms)←[0m ←[1mSELECT `characters`.* FROM `characters` WHERE `characters`.`user_id` = 1←[0m ←[1m←[35m (0.0ms)←[0m BEGIN ←[1m←[36mUser Exists (0.0ms)←[0m ←[1mSELECT 1 FROM `users` WHERE (`users`.`email` = BINARY '*****@gmail.com' AND `users`.`id` != 1) LIMIT 1←[0m ←[1m←[35mUser Exists (0.0ms)←[0m SELECT 1 FROM `users` WHERE (`users`.`username` = BINARY '******' AND `users`.`id` != 1) LIMIT 1 ←[1m←[36m (0.0ms)←[0m ←[1mROLLBACK←[0m Redirected to http://localhost:3000/members/1 Completed 302 Found in 10ms (ActiveRecord: 1.0ms) 使用方法更改此属性也很有意义.由于我正在使用Devise gem进行身份验证,因此我可以使用current_user变量来检索当前登录用户的User对象,然后只需调用current_user.email = newmail;控制器中的current_user.save. 解决方法
self.save!将在未保存时抛出异常.
此外,这可能不对: self.save return true 如果成功保存,self.save将返回true或false.所以你可能想要摆脱返回true并让返回值为self.save返回的值 在此上下文中不需要selfkeyword,也不需要返回关键字.所以这相当于你的代码: # Allows user to change email address def change_email(newmail) address = EmailVeracity::Address.new(newmail) if address.valid? self.email = newmail save true else false end end 这相当于 # Allows user to change email address def change_email(newmail) address = EmailVeracity::Address.new(newmail) if address.valid? self.email = newmail save end address.valid? end 哪个也不应该是你想要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |