hyperstack-org / hyperstack-org/hyperstack

add `create` method HyperModel collection class

Offen
#134 0 Kommentare 0 Reaktionen 1 zugewiesene Person Beansprucht von @adamcreekroad Auf GitHub ansehen
enhancement good first issue
Vorherrschende Sprache
JavaScript
Sterne
538
Forks
41
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

i.e.
```ruby
something.groups.create(name: 'new group')
# roughly the same as
new_group << Group.new(name: 'new group')
something.groups << new_group
new_group.save
```

Note that Hyperstack currently **does not save** an item when its pushed onto a collection, *unless* the collection is a `has_many :through` relationship, hence the final save above.

Like the AR create method this should return a promise / take a block that is resolved when the save completes.

Roughly code:

```ruby
def create(args = {})
args = [args] unless args.is_a? Array
items_to_save =
if (through_association = @association&.through_association)
args.collect do |attributes|
through_association.klass.new(
@association.inverse_of => @owner,
@association.source => @association.klass.new(attributes)
)
end
else
args.collect do |attributes|
@association.klass.new(attributes).tap { |item| _internal_push(item) }
end
end
Promise.new.tap do |promise|
Promise.when(items_to_save.collect(&:save)).then do
promise.resolve(items_to_save)
yield *items_to_save if block_given?
end
end
end
```

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.