Model / ActiveRecord不保存新数据

时间:2013-04-25 16:17:35

标签: ruby-on-rails ruby-on-rails-3 devise ruby-on-rails-3.2

我已确认此方法有效。基本上它从控制器接收电子邮件并更改特定用户的电子邮件。

然而,它实际上从未保存过数据。我传递了错误的电子邮件格式,如果我传递正确的电子邮件方法返回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

2 个答案:

答案 0 :(得分:1)

self.save!将在未保存时抛出异常。

此外,这可能不对:

self.save
return true

如果成功保存,self.save将返回true或false。所以你可能想摆脱return true并让返回值为self.save

返回的值 在此上下文中不需要

self关键字,return关键字也不需要。所以这相当于你的代码:

# 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

哪个也不应该是你想要的。

答案 1 :(得分:0)

似乎更好的方法是将自定义验证添加到用户模型中的电子邮件字段,设置表单以提交用户参数(使用新电子邮件,这里是rails docs来执行此操作http://guides.rubyonrails.org/form_helpers.html#binding-a-form-to-an-object)和运行类似

的东西
if @user.update_attributes(params[:user], :as => :admin)
  redirect_to @user, :notice => "User updated."
else
  render :action => 'edit', :alert => "Unable to update user."
end

在你提交行动。