Skip to content
  • Sean Doyle's avatar
    0eb9fa47
    Change `ActionText::RichText#embeds` assignment to `before_validation` · 0eb9fa47
    Sean Doyle authored
    Prior to this commit, assignment to the `embeds` association happens
    _after_ validation callbacks, so it isn't possible to incorporate Rich
    Text-related file validation.
    
    For example, consider rejecting `text/plain` files when creating
    `Message` records:
    
    ```ruby
    class Message < ApplicationRecord
      has_rich_text :content
    
      validate do
        if content.embeds.any? { |attachment| attachment.blob.content_type == "text/plain" }
          errors.add(:content, "Cannot attach text/plain files")
        end
      end
    end
    ```
    
    Without this change, the `content.embeds` association is empty at the
    time the `validate` block is evaluated, since that assignment occurs in
    a `before_save` callback on the `ActionText::Content` class.
    
    Alongside this change, the commit corrects the documentation on the
    `has_many_attached :embeds` line. The returned collection is of
    `ActiveStorage::Attachment` records and **not** `ActiveStorage::Blob`
    records as documented.
    0eb9fa47
    Change `ActionText::RichText#embeds` assignment to `before_validation`
    Sean Doyle authored
    Prior to this commit, assignment to the `embeds` association happens
    _after_ validation callbacks, so it isn't possible to incorporate Rich
    Text-related file validation.
    
    For example, consider rejecting `text/plain` files when creating
    `Message` records:
    
    ```ruby
    class Message < ApplicationRecord
      has_rich_text :content
    
      validate do
        if content.embeds.any? { |attachment| attachment.blob.content_type == "text/plain" }
          errors.add(:content, "Cannot attach text/plain files")
        end
      end
    end
    ```
    
    Without this change, the `content.embeds` association is empty at the
    time the `validate` block is evaluated, since that assignment occurs in
    a `before_save` callback on the `ActionText::Content` class.
    
    Alongside this change, the commit corrects the documentation on the
    `has_many_attached :embeds` line. The returned collection is of
    `ActiveStorage::Attachment` records and **not** `ActiveStorage::Blob`
    records as documented.
Loading