active_storage_validations icon indicating copy to clipboard operation
active_storage_validations copied to clipboard

NoMethodError: undefined method `attached?' for <#Attachment> with nested records

Open marckohlbrugge opened this issue 2 years ago • 0 comments

# promotion.rb
class Promotion
  belongs_to :product, optional: true
  has_one_attached :image
  validates :image, processable_image: true
end
# product.rb
class Product
  has_many :attachments
end
# attachment.rb
class Attachment
  belongs_to :product
  has_one_attached :image
  # no validations
end

Running the following code returns an error:

product = Product.create! …
attachment = Attachment.create! product_id: product, …

promotion = Promotion.create! product: product
=> NoMethodError: undefined method `attached?' for #<Attachment …

Unfortunately the stack trace is useless as it leads to method_missing in active_model/attribute_methods.rb

There's two surprising things happening here:

  1. Somehow the validation inside promotion.rb ends up calling .attached? on Attachment which is just a regular ActiveRecord model. It should be calling it on the image instead.
  2. Removing that validation from promotion.rb resolves the issue.

Any idea what could be going on here?

marckohlbrugge avatar Feb 23 '23 07:02 marckohlbrugge