【发布时间】:2015-06-02 14:32:55
【问题描述】:
我有一个包含用户个人资料数据的编辑表单。 User 表中的两个变量是email 和new_email。我希望编辑表单中的一个字段显示用户的email,但如果在该字段中输入了新值,我希望它不保存 到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。
【问题讨论】:
标签: ruby-on-rails ruby forms ruby-on-rails-4 controller