【问题标题】:Rails form: A field showing the value of one variable but saving it to another variableRails 表单:显示一个变量的值但将其保存到另一个变量的字段
【发布时间】:2015-06-02 14:32:55
【问题描述】:

我有一个包含用户个人资料数据的编辑表单。 User 表中的两个变量是emailnew_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


    【解决方案1】:

    您可以为输入字段提供默认值:

    &lt;%= f.email_field :new_email, value: @user.email, class: 'form-control' %&gt;

    【讨论】:

    • 谢谢,成功了。必须将控制器更改为:if params[:user][:new_email] != @user.emailsee postelseflash[:success] = "Profile updated"redirect_to @userend
    • 毕竟证明是一个问题。即使该字段中的值没有更改,它也会尝试保存到new_email。这会导致我的验证出现问题。有没有办法改变它,以便它只在输入@user.email 的现有值以外的值时才尝试写入new_email?或许我应该将if params[:user][:new_email] != @user.email 行上移一行?
    • 在输入新电子邮件地址时使用不同的强参数(然后强参数包括 new_email)和不输入时(则它不包括 new_email,因此不执行验证),解决了它
    • 是的,这是一个好方法。您仍然可以查看它,但将其过滤掉以防止保存到 db。
    【解决方案2】:

    您可以使用before_update 回调并将其值分配给new_email 字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多