我有一个包含用户个人资料数据的编辑表单。用户表中的两个变量是email
和new_email
。我想在编辑表单中的某个字段显示用户的email
,但是如果在该字段中输入了新值,我希望它不会保存< / em>到email
,而不是new_email
。所以我认为我需要new_email
的表单字段,但是会显示email
的值。我应该如何调整下面的代码才能实现这一目标?
我目前认为:
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :email %>
<%= f.email_field :new_email, class: 'form-control' %> #!!Relevant line.
<%= f.label :other_fields_like_this %>
<%= f.text_field :other_fields_like_this, class: 'form-control' %>
<%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>
控制器:
def update
@user = User.friendly.find(params[:id])
if @user.update_attributes(userupdate_params)
if params[:user][:new_email] != @user.email # That is, if: a new email address is entered, i.e. a value other then the existing value for email is entered
#save value to new_email instead of to email. How to do this?
send_confirmation_email
flash[:success] = "Your email address has not yet been updated. Please check your email for a confirmation link."
redirect_to @user
end
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def userupdate_params
params.require(:user).permit(#:email, #email I think can be removed here, since it's new_email whose value will change.
:new_email,
:other_fields_like_this,
:password,
:password_confirmation)
end
仅提供一些背景信息:在此之后,我打算通过确认电子邮件扩展此信息。如果用户点击确认链接,则new_email
的值将覆盖email
值。因此,我希望它最初保存到new_email
,并且稍后在确认之后保存到email
。
答案 0 :(得分:0)
您可以使用before_update
回调并将其分配给new_email
字段。
答案 1 :(得分:0)
您可以为输入字段提供默认值:
<%= f.email_field :new_email, value: @user.email, class: 'form-control' %>