[英]Ruby on Rails - Get polymorphic_id before_save
I have a two models: 我有两个模型:
Polymorphic 多态的
class Custo < ActiveRecord::Base
belongs_to :custavel, polymorphic: true
accepts_nested_attributes_for :custavel, allow_destroy: true
validates_presence_of :numero, :serie
validates_uniqueness_of :numero, scope: :serie
end
Another class 另一堂课
class Pagamento < ActiveRecord::Base
has_one :custo, as: :custavel
end
In general numero and serie are filled by user input, but only when the polymorphic is a Pagamento i need to fill the column numero with custavel_id . 通常, numero和serie由用户输入填充,但是仅当多态是Pagamento时,我才需要用custavel_id填充numero列。
Then, i tried it: 然后,我尝试了:
before_save :set_numero
def set_numero
return unless custavel_type == 'Pagamento'
write_attribute(:numero, custavel_id)
end
But it fails on validation because custavel_id doesn't exists yet. 但是它在验证上失败,因为custavel_id还不存在。 How to do it? 怎么做?
Modify the callback
method 修改callback
方法
before_save :set_numero
def set_numero
write_attribute(:numero, custavel_id) if custavel_type == 'Pagamento'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.