我有2種形式。如何在軌道上跳過多個驗證紅寶石
表單1我有10個字段,我正在驗證。
表格2但它只包含2個字段。
模型是一樣的。
我需要做的是:
時,他們是由表單提交的驗證領域。如果我沒有發佈任何字段,它不應該在模型中驗證。如果我發佈5個字段,它應該驗證5個字段。如果我發佈2個字段,它應該只驗證2個不是全部。
所以表格1所有10個需要驗證,形成2只2應該驗證不休息8
這裏是我的代碼:
validates :teacher_number, :title, :name, :gender, :location, :dob,
:contact_mobile, :contact_home, :street, :city, :state, :zip_code, :country,
presence: true
validates :teacher_number, uniqueness: {scope: :school_id}
validate :teacher_number_existance, :on => :create
validate :school_existance, :on => :create
下面是我的嘗試,成功地工作正常,但其大量的代碼,這是一種不好的做法。
validates :teacher_number, presence: true, if: "teacher_number && teacher_number.blank?"
validates :title, presence: true, if: "title && title.blank?"
validates :name, presence: true, if: "name && name.blank?"
validates :gender, presence: true, if: "gender && gender.blank?"
validates :location, presence: true, if: "location && location.blank?"
validates :dob, presence: true, if: "dob && dob.blank?"
validates :contact_mobile, presence: true, if: "contact_mobile && contact_mobile.blank?"
validates :contact_home, presence: true, if: "contact_home && contact_home.blank?"
validates :street, presence: true, if: "street && street.blank?"
validates :city, presence: true, if: "city && city.blank?"
validates :state, presence: true, if: "state && state.blank?"
validates :zip_code, presence: true, if: "zip_code && zip_code.blank?"
validates :country, presence: true, if: "country && country.blank?"
validates :teacher_number, uniqueness: {scope: :school_id}, if: "teacher_number && teacher_number.blank?"
validate :teacher_number_existance, :on => :create, if: "self.teacher_number && self.teacher_number.blank?"
validate :school_existance, :on => :create, if: "self.teacher_number && self.teacher_number.blank?"
編輯
更新了我的問題。
謝謝你的回答,但這不是我的情況。在我的關鍵字,'老師'或'personal_teacher'的情況下,存在隱藏的參數 – LearningROR