根据数据库中的列显示不同的消息

时间:2016-02-22 12:16:17

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

我有一个名为Transaction的模型,它有以下验证:

class Transaction < ActiveRecord::Base
  validates :paid_by, presence: true
end

默认情况下,当我提交表单而不填充此字段时,它会显示错误消息:paid_by can't be blank,但我想使其成为条件:transactions表中有一个字段名为transaction_type,因此根据transaction_type,我想生成不同的消息。

if transaction_type is A, show the A message.
if transaction_type is B, show the B message.

3 个答案:

答案 0 :(得分:2)

您不应该像这样在模型中存储错误消息。使用I18n中内置的Rails。

class Transaction < ActiveRecord::Base
  validate :validate_paid_by

private

  def validate_paid_by
    if paid_by.blank?
      errors.add(:paid_by, transaction_type)
    end
  end
end

现在你可以这样做:

en:
  activerecord:
    errors:
      models:
        transaction:
          attributes:
            paid_by:
              a: "a message"
              b: "b message"

YAML键必须与您的transaction_type.to_s值相对应。因此,如果您有type_atype_b,则必须同时调用YAML键。

答案 1 :(得分:1)

您可以通过定义自定义验证轻松完成此操作:

validate :validate_paid_by

def validate_paid_by
  if paid_by.blank?
    message = case transaction_type
    when 'A'
      'A message'
    when 'B'
      'B message'
    else
      'Default message'
    end

    errors.add(:paid_by, message)
  end
end

答案 2 :(得分:1)

最简单的方法是编写自定义验证:

class Transaction < ActiveRecord::Base
  validate :paid_by_presence_with_transaction_type

  def paid_by_presence_with_transaction_type
    if paid_by.blank?
      # whatever you have to distinguish this
      if transaction_type == TransactionType::A 
        errors.add(:paid_by,"A error message")
      else
        errors.add(:paid_by,"B error message")
      end
    end
  end
end