Skip to content

Handle Single Table Inheritance

Gabriel Cardoso edited this page Dec 10, 2015 · 4 revisions

Example

Let say you have these classes

class Product < ActiveRecord::Base
end

class SingleVariantProduct < Product
  has_one :variant
end

class MultiVariantProduct < Product
  has_many :variants
end

And you want them to appear in the same list. You can simply add this configuration to components.rb

component :products, :crud, model_type: 'Product', subclasses: ['SingleVariantProduct', 'MultiVariantProduct']

You will get a dropdown button containing the two subclasses passed to subclasses option.

_form partials

By default, Para will try to find partials using subclasses name.

For now, if you want to share the same partial you could generate form partials for each class and replace the content of the subclasses partials by:

= render partial: 'admin/products/form', locals: { resource: resource }

And add logic to your parent class partial. For example:

= para_form_for(resource) do |form|  
  = form.fieldset do
    = form.hidden_field :type, value: params[:type] || resource.type
    = form.input :name
    - if resource.is_a? SingleVariantProduct
      = form.input :variant, as: :nested_one
    - else
      = form.input :variants, :as => :nested_many
  = form.actions

Don't forget to add this line to the form

= form.hidden_field :type, value: params[:type] || resource.type
Clone this wiki locally