gpt4 book ai didi

ruby-on-rails - 初始化虚拟属性

转载 作者:行者123 更新时间:2023-12-04 06:52:23 25 4
gpt4 key购买 nike

我有一个 IncomingEmailattachments 的模型虚拟属性:

class IncomingEmail < ActiveRecord::Base  
attr_accessor :attachments
end

我想要 attachments要初始化为 [] 的虚拟属性而不是 nil这样我就可以:
>> i = IncomingEmail.new
=> #<IncomingEmail id: nil,...)
>> i.attachments << "whatever"

无需首次设置 i.attachments[] (换句话说,我希望这个虚拟属性默认为空数组而不是 nil )

最佳答案

使用 after_initialize打回来

class IncomingEmail < ActiveRecord::Base  
attr_accessor :attachments
def after_initialize
self.attachments ||= [] # just in case the :attachments were passed to .new
end
end

关于ruby-on-rails - 初始化虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2945434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com