我有一个费用模型,其中包含[: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_name
和date
放入错误消息中?
答案 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]
是访问输入数据的正确方法。