administrate-field-nested_has_many
administrate-field-nested_has_many copied to clipboard
Instantiate new records from relation
Hi !
We encountered an issue recently where we were using NestedHasMany with a polymorphic association that we'd love to fix upstream instead of monkey-patching on our end.
Problem
Since the new record was instantiated from a simple associated_class.new
, we had no way of knowing at render time what owner class the record was going to be a child of, and because of that we couldn't customize anything related to that.
Our only option was to build a new model for each of the owner classes, losing the polymorphic association or moving to STI.
Solution
By building from the owner record's relation instead of the associated class, we get a new record that's prefilled with all the data configured into the association (mainly the <x>_type
from polymorphic relations and any attributes set by where
s in the association scope).
This allows us to then customize using that data later on (in our case, to specify a dynamic collection
for a Field::Select
depending on the parent record).
Interestingly, cocoon
uses a similar pattern to render the link to add a new form.