5

我已经确认这种方法有效。基本上它从控制器获取电子邮件并更改特定用户的电子邮件。

但是,它从未真正保存数据。我传递了错误的电子邮件格式,如果我传递了正确的电子邮件方法返回 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变量来检索当前登录用户的用户对象,然后只需调用current_user.email = newmail; current_user.save控制器。

4

2 回答 2

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

这也不应该是你想要的。

于 2013-04-25T16:21:36.263 回答
0

似乎更好的方法是将您的自定义验证添加到您的用户模型中的电子邮件字段,设置您的表单以提交用户参数(使用新电子邮件,这是执行此操作的 Rails 文档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

在你提交动作。

于 2013-04-25T16:26:13.120 回答