Instantiate new records from relation #59
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 bywhere
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 aField::Select
depending on the parent record).Interestingly,
cocoon
uses a similar pattern to render the link to add a new form.