我怎样才能干掉我的验证码?我有一个Discussion
模型,它有一个category
和status
字段。状态值取决于类别值。例如,category == 'question'
只能在STATUSES[:question]
中有状态的讨论。
STATUSES = {
question: %w[answered],
suggestion: %w[pending planned started completed declined],
problem: %w[started solved]
}
validates :status, allow_blank: true, inclusion: { in: STATUSES[:question] }, if: lambda { self.category == 'question' }
validates :status, allow_blank: true, inclusion: { in: STATUSES[:suggestion] }, if: lambda { self.category == 'suggestion' }
validates :status, allow_blank: true, inclusion: { in: STATUSES[:problem] }, if: lambda { self.category == 'problem' }
我在用Rails 3。
最佳答案
:inclusion :in
接受lambda本身:
validates :status, inclusion: { in: lambda { |o| STATUSES[o.category.to_sym] } }
文档:http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of