本文介绍了对象.有效吗?返回 false 但 object.errors.full_messages 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对无法保存的对象感到困惑,简化模型是
I'm confuse about objects that I can't save, simplified model is
class Subscription < ActiveRecord::base
belongs_to :user, :class_name => "User", :foreign_key => "user_id"
has_many :transactions, :class_name => "SubscriptionTransaction"
validates_presence_of :first_name, :message => "ne peut être vide"
validates_presence_of :last_name, :message => "ne peut être vide"
validates_presence_of :card_number, :message => "ne peut être vide"
validates_presence_of :card_verification, :message => "ne peut être vide"
validates_presence_of :card_type, :message => "ne peut être vide"
validates_presence_of :card_expires_on, :message => "ne peut être vide"
attr_accessor :card_number, :card_verification
validate_on_create :validate_card
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add_to_base message
end
end
end
def credit_card
@credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:type => card_type,
:number => card_number,
:verification_value => card_verification,
:month => card_expires_on.month,
:year => card_expires_on.year,
:first_name => first_name,
:last_name => last_name
)
end
end
在我的订阅控制器中
if subscription.save
# do something
else
debugger # means breakpoint where i try subscription.errors.full_messages
# do something else
end
我尝试使用 ruby-debug 来添加一个断点来进行一些测试
I tried to use ruby-debug for this adding a breakpoint where i do some tests
subscription.valid? #=> false
subscription.errors.full_messages #=> []
subscription.save! #=> ActiveRecord::RecordInvalid (Validation failed:)
这说明 ActiveRecord 不允许使用 save 方法.不幸的是我不知道为什么这个对象是无效的.
which explains that ActiveRecord doesn't allow the save method. Unfortunately i can't know why the object is invalid.
如果您有任何想法,谢谢.
If you have any idea, thank you.
推荐答案
我也遇到了同样的问题.起初我的模型中有这样的代码:
I had the same problem. At first I had such code in my model:
before_validation :set_some_param
def set_some_param
self.some_param = some_value
end
在我将其更改为:
before_validation :set_some_param
def set_some_param
self.some_param = some_value
true
end
我可以看到我的错误.
也许你的代码中有类似的东西?
Maybe you have something simular in your code?
这篇关于对象.有效吗?返回 false 但 object.errors.full_messages 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!