Rails验证 - 包含相关模型属性的自定义错误消息

时间:2013-05-17 09:09:00

标签: ruby-on-rails-3.2

我有一个费用模型,其中包含[:user_id:activity_id:date,....等属性。

关系是:

expense belongs_to user
expense belongs_to activity

我有以下验证。

validates :activity_id, uniqueness: scope: [:user_id, :date], message: "Expense for 'activity_name' on date '1/1/2012' is already entered"

如何将activity_namedate放入错误消息中?

2 个答案:

答案 0 :(得分:0)

您可以使用:message属性。这是内联方法。

validates :activity_id, :uniqueness => {:scope => [:user_id, :date], :message => "Expense for "+ activity_name + " on date " + date + " is already entered"}

答案 1 :(得分:0)

另一种方法(非内联)是:

在型号代码中:

validates :activity_id, uniqueness: => {scope: [:user_id, :date], :message => "error is here"}

在视图代码中:

  = form_for(@expense) do |f|
    - if @expense.errors.any?
      = pluralize(@expense.errors.count, "error")
        prohibited this link from being saved:

        %ul
          -@expense.errors.full_messages.each do |msg|
            - if msg[0,12] == "error is here"
              = "Expense for "+ params[:activity_name] + " on date " + params[:date] + " is already entered"

params[:activity_name]是访问输入数据的正确方法。