jam*_*mes 5 ruby activerecord ruby-on-rails
在Ruby中,我将如何运行一个验证,该验证表明模型属性如果以前是Y,则只能是X?该示例将是status采用in-progress或的属性complete。我想说的是,当用户标记对象状态时,可以始终对其进行标记in-progress,但是只有在complete第一次标记时才可以对其进行标记in-progress。
validate :status_change
def status_change
unless self.status == "complete" && #here i want to say self.status used to be "in progress"
errors[:base] << "Can only mark object complete after it was first marked in progress"
end
end
Run Code Online (Sandbox Code Playgroud)
请考虑使用ActiveModel::Dirty
它提供了跟踪这些变化的方法。
before_update :status_change
def status_change
unless status == "complete" && status_was == "in-progress"
errors[:base] << "Can only mark object complete after it was first marked in progress"
end
end
Run Code Online (Sandbox Code Playgroud)
另外,这里不需要使用self.关键字。