我正面临着当前的问题。我有一个Paperclip处理器,在使用嵌套语法parent.children.create(file: File)
时需要访问其现有的父对象属性。我知道我可以使用
child = parent.children.new
child.file = file
child.save
并且这种方式可以访问父项,但由于我是一个大项目并且在整个项目中都有parent.children.create
,如果我能找到原始问题的解决方案会更好。
我的解析器:
class Paperclip::Processors::ChildFileParser < ::Paperclip::Processor
def make
if @attachment.instance.parent.parent_attribute
begin
some_logic
rescue => e
Rails.logger.error("error")
end
end
Paperclip::TempfileFactory.new.generate
end
end
因此,当试图在@attachment.instance.parent.parent_attribute
语句中访问if
时,它将给出错误there is no parent_attribute for nil
。在构建子对象时执行上述方法。
编辑1:
只是添加关系。
class Parent
has_many :children, class_name: 'Child'
end
class Child
belongs_to :parent
end
我不完全确定这是你所追求的,尽管使用这个代码可以避免你所面对的NoMethodError
s。如果父级确实存在,即使使用build
/ create
,您也应该能够从子级访问它。例如。
c = parent.build_child
c.parent # => #<Parent id: ...>
因此,如何解决以下问题之一:
# ref https://api.rubyonrails.org/classes/Object.html#method-i-try
if @attachment.instance.parent.try(:parent_attribute)
...
end
# ref https://docs.ruby-lang.org/en/2.6.0/syntax/calling_methods_rdoc.html#label-Safe+navigation+operator
if @attachment.instance.parent&.parent_attribute
...
end
# both use safe navigation operators and are essentially short hand for:
# @attachment.instance.parent && @attachment.instance.parent.parent_attribute
如果没有父母,这些将返回nil
,因此为了步骤到Paperclip::TempfileFactory.new.generate
是假的。
你也可以使用delegate
:
# child.rb
delegate :parent_attribute, to: :parent, allow_nil: true
这将允许您安全地拨打:
if @attachment.instance.parent_attribute
# ...
end
注:如果在@attachment.instance
上调用方法时有助于澄清事情,你也可以提供委托前缀。
希望有所帮助 - 让我知道你是如何得到的,或者如果你有任何问题。