0
votes

I have a model hook that returns a list of reviews from the data store. On that same page, I have a review form. When the form is submitted, I call an action on the controller and I need to call createRecord() on the store. Normally I would pass a created record from a model hook but my model hook is already taken. What is the best approach here?

2

2 Answers

4
votes

It would be a lot better to create this record in the model hook and use it across the form, e.g. for making validations if needed. You can use Ember.RSVP.hash for having multiple models fetched in model hook:

model: function() {
  data = {
    reviews: store.find("review"),
    newReview: store.createRecord("review")
  };

  return Ember.RSVP.hash(data);
}

Than, in your setupController:

setupController: function(controller, model) {
  // all your data is in model hash
  controller.set("model", model.reviews);
  controller.set("newReview", model.newReview);
}

Thanks to that, you would have your newReview object from the beginning in the controller. You can set bindings directly to it in your form and make validations on the fly. It's better way, as it does not need to copy data from the form to the object by hand, but rather take advantage from ember bindings system, like that.

All you would have to do in your action would be:

actions: {
  save: function() {
    this.get("newReview").save();
  }
}
1
votes

When the form is submitted, I call an action on the controller and I need to call createRecord() on the store. Normally I would pass a created record from a model hook but my model hook is already taken.

I don't know what you mean by "pass a created record from the model hook". Pass from where to where? If you want to create a record, just create it in the action. Then you can update the controller's model with the new record:

// controller
actions: {
    addReview() {
        function create()     { return store.createRecord('review', ...); }
        function push(review) { model.pushObject(review); }

        var store = this.get('store');
        var model = this.get('model');

        create() . save() . then(push);
    }
}

Or something similar.