简体   繁体   English

如何在不验证其余属性/列的情况下验证和更新1个属性/列?

[英]How can I validate and update 1 attribute/column, without validating the rest?

I want my users to be able to update their email addresses, if they authenticate themselves. 我希望我的用户能够通过身份验证来更新其电子邮件地址。

My code looks something like this... 我的代码看起来像这样...

    @user = User.find_by_email(params[:user][:old_email].downcase)

    if @user
        if @user.authenticate(params[:user][:password])
            @user.email = params[:user][:email]

            if @user.update_attributes(email: params[:user][:email])

Something along those lines. 遵循这些原则。 Basically the params are the old_email, the email which the user wants to change to, and their password. 基本上,参数是old_email,用户想要更改的电子邮件以及他们的密码。 We pull the record that matches their old_email (current email). 我们提取与其old_email(当前电子邮件)匹配的记录。 Then we verify the password matches. 然后,我们验证密码是否匹配。 If so, we want to change the email and the email only, IF of course the email meets the criteria in our model for the :email column. 如果是这样,我们当然只希望更改电子邮件和电子邮件,如果该电子邮件符合我们的模型中:email列的条件,则该电子邮件是必需的。

The problem I'm having is, when I get to @user.update_attributes(em... I get the following error 我遇到的问题是,当我到达@user.update_attributes(em...我得到以下错误

"Password is too short (minimum is 6 characters)"

I don't want it to verify on password, password should not even be involved in the update whatsoever. 我不希望它通过密码进行验证,即使更新也不应涉及密码。 I'm only interested in the changing the email here. 我只对更改此处的电子邮件感兴趣。 I want validation only on the email field, and none of the others, and I only want to update the email field. 我只想在电子邮件字段上进行验证,而没有其他验证,我只想更新电子邮件字段。 How can I achieve this? 我该如何实现?

You can update specific column by #update_columns . 您可以通过#update_columns更新特定的列。 It updates the attributes directly in the database issuing an UPDATE SQL statement and sets them in the receiver. 它通过发出UPDATE SQL语句直接在数据库中更新属性,并在接收UPDATE SQL设置。

It will skip validations and callbacks . 它将跳过 验证回调

@user.update_columns(email: params[:user][:email])

Remember to sanitise the email address before updating. 在更新之前,请记住清理电子邮件地址。

Validation belongs in the model but as you need to validate in controller, define a private action: 验证属于模型,但是您需要在控制器中进行验证时,定义一个私有操作:

private
  def valid_email?(email)
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    email.present? && (email =~ VALID_EMAIL_REGEX)
  end

Then your condition check would be: 那么您的条件检查将是:

if @user.authenticate(params[:user][:password]) && valid_email?(params[:user][:email])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM