加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 验证除Rails中的一个属性之外的所有属性

发布时间:2020-12-17 03:49:47 所属栏目:百科 来源:网络整理
导读:我正在尝试使用有效的模型进行自定义验证?方法.我需要运行此模型的所有验证,但密码除外. 像这样的东西: @resource = SalesPartner.new(permitted_params.merge(parent: current_sales_partner))respond_to do |format| if @resource.valid?(except: :passw
我正在尝试使用有效的模型进行自定义验证?方法.我需要运行此模型的所有验证,但密码除外.

像这样的东西:

@resource = SalesPartner.new(permitted_params.merge(parent: current_sales_partner))

respond_to do |format|

  if @resource.valid?(except: :password)
    @resource.generate_authentication_token

    SalesPartnerMailer.mail_new_sales_partner(@resource.email,{ auth_token: @resource.authentication_token,id: @resource.id,level: @resource.level }
    ).deliver

    flash[:success] = "#{@resource.level} criado com sucesso."
    format.html { render "#{@path}/index" }
  else
    logger.log_and_alert_save_error(@resource,flash,"Ocorreu um erro ao salvar.")
    format.html { render "#{@path}/new" }
  end

end

那可能吗?

感谢大家!

解决方法

这里的任何方式都是您可以在上下文的帮助下完成的方式.假设您有一个用户模型,并且您想要验证某些字段.

validates_presence_of :name,: email,on: :special_context
validates_presence_of :name,:email,:password

有了上面2行,你现在可以在下面这样做

@user.valid?(:special_context)

以上将验证名称和电子邮件字段.如果你现在写,

@user.valid?

这将在您编写时对名称,电子邮件和密码字段执行在线验证.

阅读valid?(context = nil)以了解上下文.

Runs all the validations within the specified context. If the argument is false (default is nil),the context is set to :create if new_record? is true,and to :update if it is not.

Validations with no :on option will run no matter the context. Validations with some :on option will only run in the specified context.

请将此documentation作为官方示例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读