在一个模型的视图中验证2个表单字段

时间:2014-11-13 09:09:55

标签: validation ruby-on-rails-4 logic

我不明白。如何在视图中单独验证2个表单域。今天我了解到,模型中的验证总是验证模型中的所有对象,而不是通过参数给出的对象。现在我试图找出,如何只验证通过表单字段给出的对象。

HTML

    %td
      = form_for opportunity, remote: true do |f|
        = f.text_field :boni_score, placeholder: '0.0 - 6.0'
        = f.submit "Bonität hinzufügen", class: "block btn btn-sm btn-primary marginTop"
    %td
      = form_for opportunity, remote: true do |f|
        = f.text_field :schufa_score, placeholder: '0-9999'
        = f.text_field :schufa_range, placeholder: 'A-P oder Unbekannt', class: 'marginTop'
        = f.submit "Speichern", class: "block marginTop btn btn-sm btn-info"

验证

    SCHUFA_RANGE =* ('A'..'P')
    SCHUFA_RANGE << 'Unbekannt'

    validates :schufa_range, inclusion: SCHUFA_RANGE, on: :update, if: :boni_score_blank?
    validates :schufa_score, numericality: { only_integer: true }, length: { maximum: 9999, minimum: 0 }, on: :update, if: :boni_score_blank?
    validates :boni_score, numericality: { only_integer: false }, length: { maximum: 6, minimum: 0 }, if: :schufa_blank?

    def boni_score_blank?
      boni_score.blank?
    end

    def schufa_blank?
      schufa_range.blank? || schufa_score.blank?
    end

当我按下提交按钮时,那个洞认为有效。事实上,我没有得到这个的逻辑。是否可以验证当前在param中的每个对象?

1 个答案:

答案 0 :(得分:0)

好的伙计们,我有一个解决方案

validates :schufa_range, inclusion: SCHUFA_RANGE, on: :update, if: proc { |opportunity| opportunity.schufa_range_changed? }
validates :schufa_score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 9999 }, on: :update, if: proc { |opportunity| opportunity.schufa_score_changed? }
validates :boni_score, presence: true, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 6 }, on: :update, if: proc { |opportunity| opportunity.boni_score_changed? }

现在,当model.objects发生变化时,验证就会发生。