0

I have a model Medium which through STI has two subclasses

class Medium < ApplicationRecord
end

class Image < Medium
end

class Video < Medium
end

These two subclasses can through a many-to-many relationship be associated with instances of a Brand. The joint table is called Ìllustrations.

class Brand < ApplicationRecord
  has_many :illustrations, as: :illustrateable, dependent: :destroy
  has_many :images, through: :illustrations, source: :illustrateable, source_type: 'Image'  
  has_many :videos, through: :illustrations, source: :illustrateable, source_type: 'Video'
end

class Illustration < ApplicationRecord
  belongs_to :illustrateable, polymorphic: true
  belongs_to :brand
end

When I want to create a record in the joint table using the Administrate gem, the interface looks very neat.

enter image description here

This uses the following Administrate code:

class IllustrationDashboard < Administrate::BaseDashboard
  ATTRIBUTE_TYPES = {
    illustrateable: Field::Polymorphic.with_options(
      classes: [Image, Video]
    ),
    brand: Field::BelongsTo,
    id: Field::String,
    created_at: Field::DateTime,
    updated_at: Field::DateTime,
  }.freeze
end

The issue that I'm having is that Administrate always saves the illustrateable_type: "Medium", not Image or Video. How can I fix this? Here's how the params look like:

#<ActionController::Parameters {"authenticity_token"=>"ySVJJ5f6lnWO97UNE1Fh8k7mfKu57pu8X1FHL0xgraY3WwvFqTSTNAxBR8AQ4TGzxZMjHIj8St1AJkbzcBWsSg", "illustration"=>{"illustrateable"=>{"type"=>"Administrate::Field::Polymorphic", "value"=>"gid://novoglobo/Image/c35498dc-8209-419b-a43d-5ca26bc11beb"}, "brand_id"=>"3bef71ad-c41a-4b96-9a91-6e6db847009c"}, "commit"=>"Create Illustration", "controller"=>"admin/illustrations", "action"=>"create"} permitted: false>
migu
  • 4,236
  • 5
  • 39
  • 60
  • Is your `Illustration` model defined correctly? Brands are illustrateable, and you have both `Illustration belongs_to :brand` and `Illustration belongs_to :illustrateable`, which I think is the same thing twice. My polymorphism is rusty, but I think you should not use it, and instead do: `Illustration belongs_to :brand`, `Illustration belongs_to :medium`, `Brand has_many :images, through: :illustrations, source: :medium, class_name: "Image"`, and `Brand has_many :videos, through: :illustrations, source: :medium, class_name: "Video"`. – pablobm Nov 03 '21 at 07:43
  • OK, I see you answered this yourself at https://github.com/thoughtbot/administrate/issues/2045. – pablobm Nov 05 '21 at 07:19

0 Answers0