2016-01-16 149 views
6

我試圖讓用戶更改他們的電子郵件地址,其中設計使用作爲其唯一的用戶名。即使更新沒有提供任何錯誤,也不會更改數據庫中用戶的電子郵件地址。設計更改電子郵件不更新電子郵件

下面是代碼的相關部分:

形式:

<%= f.fields_for :user_account, @user.user_account do |user_account| %> 
<p>Edit email address for account: <%= @user.user_account.email %></p> 
<div class="field"> 
    <%= user_account.label :new_email %><br /> 
    <%= user_account.text_field :email, autocomplete: "off", value: nil %> 
</div> 
<div class="field"> 
    <%= user_account.label :password %> <i>(please confirm the password associated with this account)</i><br /> 
    <%= user_account.password_field :current_password, autocomplete: "off" %> 
</div> 
<%= hidden_field_tag 'form', 'email' %> 
<div class="actions"> 
    <%= user_account.submit "Edit" %> 
</div> 

控制器:

def update 
respond_to do |format| 
if params[:form] == 'email' 
    if @user.user_account.valid_password?(params[:user][:user_account_attributes][:current_password]) 
     if @user.update(user_params) 
     format.html { redirect_to user_path(@user), :notice => 'your new email has been saved' } 
     format.json { render :show, status: :ok, location: @user } 
     else 
     format.html { render :edit } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    else 
     format.html { redirect_to edit_email_path(@user), :notice => 'incorrect password (email)' } 
    end 
else ... 

的user_params方法:

def user_params 
params.require(:user).permit(
    :first_name, :middle_initial, :last_name, 
    :linkedin, :website, :facebook, :video, :phone_number, 
    :address_1, :address_2, :city, :zip_code, 
    :image, :number, :years_practicing, :neighborhood, :biography, :price, :status, 
    user_employments_attributes: [:id, :user_id, :company, :position, :start_date, :end_date, :info, :_destroy], 
    user_educations_attributes: [:id, :user_id, :school, :degree_title, :start_date, :end_date, :info, :_destroy], 
    user_account_attributes: [:id, :user_id, :email, :password, :password_confirmation, :_destroy], 
    user_category_ids:[]) 
end 

用戶帳戶型號:

class UserAccount < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # , :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, :confirmable, 
    :recoverable, :rememberable, :trackable, :validatable 
    belongs_to :user 
end 

回答

0

我不知道,但我想,在你的用戶模型應該有

accepts_nested_attributes_for :user_account 
+0

是的,已經有那個:( – chris

5

好了,事實證明,新的電子郵件地址已被保存as:unconfirmed_email,但是這並沒有改變鏈接帳戶的任何功能,因爲該帳戶仍舊以舊電子郵件存儲爲:email。

因此,我不得不這樣做

user.confirmed_at = nil 
user.save(:validate => false) 

,以便用戶確認郵件被重發,並讓登錄表單不再接受舊密碼。

+0

我用了一個調用'confirm()'。同樣的想法。 –