如何在rails上设置验证方法ruby的顺序?

时间:2016-04-29 17:02:41

标签: ruby-on-rails ruby

我是Ror初学者。有一个模型 Lectur e,我想首先验证开始时间和结束时间的格式,然后检查结束时间是否在开始时间之后。它在格式有效时效果很好但是一旦格式错误就会出现:未定义的方法`<'为零:NilClass。如何在格式有效时触发 start_must_be_before_end_time ?谢谢!

以下是代码:

class Lecture < ActiveRecord::Base
belongs_to :day
belongs_to :speaker
validates :title, :position, presence: true



validates :start_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
         message: "Incorrect time format" }


validates :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
        message: "Incorrect time format" }


validate :start_must_be_before_end_time

private
def start_must_be_before_end_time
    errors.add(:end_time, "is before Start time") unless start_time < end_time
end

end

2 个答案:

答案 0 :(得分:2)

validates方法定义的验证顺序无法保证。但是,使用validate方法定义的custom validators保证订单。

来自docs:

  

您可以为每个类方法传递多个符号,相应的验证将以与注册时相同的顺序运行

替代地

如果所有其他验证都通过,则只能运行验证方法:

validate :start_must_be_before_end_time, :unless => Proc.new { |obj| obj.times_valid? }

# Then, define `times_valid?` method and check that start_time and end_time are valid

答案 1 :(得分:-1)

你可以采取另一种方式:

theBoard = {1:' ', 2:' ', 3:' ', 4: ' ', 5:' ', 6: ' ', 7:' ', 8:' ', 9:' '}

@app.route('/reset', methods=["GET", "POST"])
def reset():
    for i in range (1,9):
         theBoard[i] == ' '
    return render_template("test.html", theBoard=theBoard)

@app.route('/play', methods=["GET","POST"])
def test1():
     return render_template("test.html", theBoard=theBoard)

@app.route('/play1', methods=["GET", "POST"])
def test():
    if gameover(theBoard):
       True
       return 'the game is over1'
    else:
        x = request.form['move']
        move = int(x)
        valid_moves = [1,2,3,4,5,6,7,8,9]
    if move not in valid_moves:
        return 'you did not specify a valid move, please try again!'
    elif theBoard[move] != ' ':
        return 'you can not play that space, it is taken'
    else:
        theBoard[move] = 'X'
        if gameover(theBoard):
            True
            return 'the game is over2'
        if winning_X(theBoard):
        <and much more code - this part works>
相关问题