这就是在我的模型中调用我想要的错误的方法:
validate :number_of_clients
def number_of_clients
errors[:base] << "You cannot add another client" if
Authorization.current_user.plan.num_of_clients <= Authorization.current_user.clients.count
end
即使我将错误行更改为以下内容,也会产生相同的结果:
errors.add(:base, "You cannot add another client")
errors.add_to_base("You cannot add another client")
这是解析错误消息的方式(在_error_messages部分中):
<% if object.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(object.errors.count, "error") %>
prohibited this user from being saved:</h2>
<p> There were problems with the following fields:</p>
<ul>
<% object.errors.full_messages.each_full do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
这是我的html中显示错误消息的方式:
There were errors: base: You cannot
add another client
编辑1:我想要发生的是在实际消息中删除文本“base:”。所以我想说There were errors: You cannot add another client
。
答案 0 :(得分:0)
尝试
errors.add_to_base("Your message")
答案 1 :(得分:0)
validate :number_of_clients
def number_of_clients
errors.add(:base, "You cannot add another client") if Authorization.current_user.plan.num_of_clients <= Authorization.current_user.clients.count
errors.blank? #You have to return false to not proceed
end
if:base出现,为什么你不尝试这样做:
MyClass < ActiveRecord::Base
attr_reader :my_mistery_field
validate :number_of_clients
def number_of_clients
errors.add(:my_mistery_field, "You cannot add another client") if Authorization.current_user.plan.num_of_clients <= Authorization.current_user.clients.count
errors.blank? #You have to return false to not proceed
end
end
在您的文件en.yml(或lang.yml,无论您的lang默认应用程序)
en.yml
en:
activerecord:
attributes:
my_class:
my_mistery_field: "Don't touch on my mistery field"
当然用于其他事情,但谁告诉我们不能欺骗Rails?
希望它能以某种方式帮助你。
答案 2 :(得分:0)
我通过在base: ""
文件中的activerecord.attributes
下的相应位置添加条目en.yml
来解决此问题。