【问题标题】:validate only on some method rails仅在某些方法轨上验证
【发布时间】:2015-12-24 08:48:35
【问题描述】:

基于 Rails 验证 docs。我只需要在更新时验证fullname 字段

# encoding: utf-8
class User < ActiveRecord::Base
  GENDER_MALE = true
  GENDER_FEMALE = false

  attr_accessor :password_confirm,
                :term,
                :year, :month, :day,
                :captcha

  validates :username, presence: {message: "Bạn phải nhập tài khoản"},
                      uniqueness: {message: 'Tài khoản đã tồn tại'}, :on => :update
  # validates :password, presence: {message: "Bạn phải nhập mật khẩu"},
  #                     confirmation: {message: 'Mật khẩu không chính xác'}
  # validates :password_confirmation, presence: {message: "Bạn phải nhập xác nhận mật khẩu"}
  # validates :fullname, presence: {message: "Bạn phải nhập họ tên"}
  # validates :email, presence: {message: "Bạn phải nhập email"},
  #                   uniqueness: {message: "Email đã tồn tại"}
  # validates :email, format: {with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, message: "Email không đúng định dạng"},
  #                   unless: "email.blank?"
  # validates :term, acceptance: {message: "Bạn phải đồng ý điều khoản"}
  # # validates :gender, acceptance: {accept: [0,1], message: "Giới tính không hợp lệ"}
  # validate :_birthday_validator
  # validate :_captcha_validator
  #
  # before_save :_encrypt_password

  def signup
    self.birthday = "#{year.to_s}-#{month.to_s}-#{day.to_s}"
    self.save
  end

  def self.human_attribute_name(attr, option = {})
    "" || super
  end



  protected
    def _encrypt_password
      self.password = Digest::MD5::hexdigest(password)
    end

  private
    def _birthday_validator

      unless year.present? && month.present? && day.present?
        errors.add(:birthday, 'Bạn phải nhập ngày sinh')
      else
        errors.add(:birthday, 'Ngày sinh không hợp lệ') unless Date.valid_date?(year.to_i, month.to_i, day.to_i)
      end
    end

    def _captcha_validator
      if !(captcha.nil?)
        errors.add(:captcha, "Mã xác nhận không hợp lệ") if captcha == false
      end
    end
end

据了解,此验证规则仅在我调用 update 方法时运行,但我不知道为什么此规则一直运行 谁能告诉我为什么或者我错过了什么?

Ps:Rails 是否只能验证用户定义的方法,例如 validates :username, presence: true, only: [:my_func]

【问题讨论】:

  • 邮政编码,不是代码截图。
  • @SergioTulentsev 我更新了上面的模型代码,请帮助我
  • 我自己找到了答案。上面的代码通过了验证规则,因为当我调用update 时,数据库中不存在用户对象,它是一条新记录,但on: :update 仅适用于数据库中存在的对象。
  • on: :update 挂钩仅在更新现有记录时被调用,是的。

标签: ruby-on-rails validation


【解决方案1】:

一种方法是设置一个virtual attribute,您只能在signup 方法中填充它:

#app/models/user.rb
class User < ActiveRecord::Base
   attr_accessor :should_validate
   validates :fullname, presence: true, on: :update, if: "should_validate.present?" 
end

这样,只有当你使用signup时,你才能为should_validate赋值:

def signup
   self.birthday = "#{year.to_s}-#{month.to_s}-#{day.to_s}"
   self.should_validate = true
   self.save
end

【讨论】:

  • 很棒的逻辑...可能对用户有用:)
【解决方案2】:

你可以使用类似的方法

validate :fullname , on: :update

def fullname
   if self.fullname.present?
      true
   else
      false
   end
end

【讨论】:

  • 感谢您的回答,但也许我的问题并不清楚。我想知道如何仅对用户定义方法运行验证。例如:我定义了一个方法signup,在这个方法中我调用self.save 来保存到数据库,但是当我调用@user.signup时我希望验证规则只有符文
  • 验证 :fullname , , :if => lambda { self.exists? }
  • 验证 :fullname, :if => { controller.action_name == "signup"}
  • controller.action_name == 'signup' 不适合我,我收到错误 undefined local variable or method controller
猜你喜欢
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多