Ruby on rails Rails 4-显示非Activerecord模型中的错误

Ruby on rails Rails 4-显示非Activerecord模型中的错误,ruby-on-rails,ruby-on-rails-4,model,Ruby On Rails,Ruby On Rails 4,Model,为了管理表单,我有一个无表模型(即不保存在数据库中)。按照一集中的说明进行操作后,它基本上可以正常工作: class PaymentRequest include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :request_id, :amount, :description, :reference, :char

为了管理表单,我有一个无表模型(即不保存在数据库中)。按照一集中的说明进行操作后,它基本上可以正常工作:

class PaymentRequest
    include ActiveModel::Validations
    include ActiveModel::Conversion
    extend ActiveModel::Naming

    attr_accessor :request_id, :amount, :description, :reference, :charge_date
    validates :request_id, presence: true
    validates :amount, presence: true, numericality: true
    validates :charge_date, presence: true

    def initialize(attributes = {})
        attributes.each do |name, value|
            send("#{name}=", value)
        end
    end

    def persisted?
        false
    end
end
当我执行
PaymentRequest.new().valid?
时,我得到
false
(如果它实际有效,则反之亦然)

但是,我没有得到任何错误消息:当运行
PaymentRequest.new().errors.messages时,我得到一个空哈希
{}

我错过了什么


谢谢

您的
错误。由于您使用的是
new
方法:
PaymentRequest.new()
,因此消息
哈希为空,因此您没有尝试在数据库中保留任何内容

在将对象持久化到数据库中之前会调用验证,例如,当您尝试保存对象时,或者当您调用验证方法时

在您的示例中,如果您尝试保存付款对象,则您的
错误。消息
散列将填充相应的消息:

p = PaymentRequest.new()
p.errors.messages
# => {} # empty hash because you did not try to save the p object yet
p.save # at this point validations are happening
p.errors.messages 
# => {:charge_date =>["can't be blank"]} . . . 
或者,您可以使用:
create
方法:

p = PaymentRequest.create()
p.errors.messages 
# => {:charge_date =>["can't be blank"]} . . . 
然后,您将在
errors.messages
hash中看到错误消息,因为
create
方法试图保存对象


要回答您的另一个问题,
PaymentRequest.new().valid?
false
,因为保存/持久化之前的所有内容都是
false
<代码>有效?
将在对象成功保存时返回
true

错误只会在调用验证方法后填充,如
有效?
。如果这样做,您将得到与ActiveRecord对象类似的错误消息

下面是一个示例,使用您在问题中提供的
PaymentRequest
代码:

p = PaymentRequest.new
p.errors.messages # => {}
p.valid? # => false
p.errors.messages # => {:request_id=>["can't be blank"],... 

请注意
errors
最初是空的,但在调用
valid?
时会立即填充。

得到它-我在控制台中按顺序运行2进行测试。将它保存到一个变量会产生不同!我本可以更清楚地表明,我没有将其保存到DB(因此保持为false)。有效吗?无论是否持久化(因为在开始时包含/扩展)。