我正在使用Rails 4.2.7。我的模型验证规则
class MyObjectTime < ActiveRecord::Base
validates :time_in_ms, numericality: { greater_than: 0 }
我想编写自定义错误消息,所以在我的config / locales / en.yml文件中我包含了
en:
activerecord:
attributes:
my_object:
name: "Name"
my_object_time:
time_in_ms: "Time"
errors:
models:
my_object_time:
attributes:
time_in_ms:
not_a_number: "This field must be a number greater than zero."
blank: "This field must be a number greater than zero."
但是当我的对象无法验证时,我的@ my_object_time.errors.full_messages数组中不包含此自定义错误消息。相反,包括的是
Must be greater than 0
在配置文件中写入的正确规则是什么,以便我可以自定义此错误消息?
答案 0 :(得分:1)
您可以直接在模型中自定义消息。
template<typename F, typename... Tail>
auto measureAndExecute(F f, Tail&&... tail) -> typename std::result_of<F(Tail&&...)>::type {
std::chrono::high_resolution_clock::time_point time1 = std::chrono::high_resolution_clock::now();
auto res = f(std::forward<Tail>(tail)...);
std::chrono::high_resolution_clock::time_point time2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(time2 - time1).count();
std::cout << duration << " milliseconds" << std::endl;
return res;
}
或在class MyObjectTime < ActiveRecord::Base
validates :time_in_ms, numericality: { greater_than: 0 }, message: 'my customized message.'
end
文件中,您需要为en.yml
greater_than: