【问题标题】:How do I get rid of the word "base: " from my error message in Rails 3?如何从 Rails 3 中的错误消息中删除“base:”一词?
【发布时间】:2011-02-20 12:08:20
【问题描述】:

这就是我想要的错误在我的模型中的调用方式:

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

【问题讨论】:

    标签: ruby-on-rails-3 error-handling


    【解决方案1】:

    试试

    errors.add_to_base("Your message")
    

    【讨论】:

    • 实际上,当我这样做时,我得到了这个:DEPRECATION WARNING: Errors#add_to_base(msg) has been deprecated, use Errors#add(:base, msg) instead.
    • 好吧,我猜你用的是 rails 3.0。你可以尝试显示 msg.to_yaml 吗?
    • 在这种情况下我该怎么做?
    【解决方案2】:
        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
    

    如果 :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?

    希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      我通过在我的en.yml 文件中的activerecord.attributes 下的适当位置添加一个条目base: "" 解决了这个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多