开发者

How can I return the parent's attachment if the child's is nil with Paperclip

开发者 https://www.devze.com 2023-04-03 13:54 出处:网络
I am using Paperclip to defined an attachment called badge, both on a child model and the parent model defined through a belongs_to.I want to override @instance.badge such that it returns the model\'s

I am using Paperclip to defined an attachment called badge, both on a child model and the parent model defined through a belongs_to. I want to override @instance.badge such that it returns the model's badge if it is availabl开发者_开发问答e, otherwise it returns the parent's badge.

I started by doing the following until I realized that the read_attribute was always returning nil and using the parent badge. Is there a way to read the result of the badge method and if that returns nil, use the parent's badge method instead?

I'd prefer to keep the method named badge too, instead of having a separate child_or_parent_badge method.

def badge
  read_attribute(:badge) || parent.badge
end


Naming the method badge will make your life much more complicated, it makes more sense to name the helper for what it does and leave the attachment name the same so you can access it directly.

class Parent < ActiveRecord::Base
  has_many :childs
  has_attached_file :badge
end

class Child < ActiveRecord::Base
  belongs_to :parent
  has_attached_file :badge

  def resolve_badge
    badge || parent.badge
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消