Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model/ActiveRecord not saving new data

I have confirmed that this method works. Basically it takes the email from controller and changes the email of the specific user.

However it never actually saves the data. I pass a wrong email format and it returns false if I pass the correct email method returns true which means it assigned a new email and called safe.

# 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

I checked the logs first for any hints but nothing all i get is:

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)

Also does it make much sense to have a method to change this attribute. Since I'm using Devise gem for authentication I can use current_user variable to retrieve the User object for currently logged in user and then just call current_user.email = newmail; current_user.save in the controller.

like image 647
Sterling Duchess Avatar asked Nov 12 '22 06:11

Sterling Duchess


1 Answers

self.save! will throw an exception when not saved.

Also, this might not be right:

self.save
return true

self.save returns true or false according if it successfully saved or not. So you might want to get rid of return true and let the return value be the one returned from self.save

selfkeyword is not needed in this context, neither the return keywords. So this is equivalent to your code:

# 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

That is equivalent to

# 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

Which also should not be what you want.

like image 78
fotanus Avatar answered Nov 15 '22 04:11

fotanus