0
votes

I am trying to create a record and on the server side I am using rails. The rails validations are failing and I am returning a 422 status code but when I delete it in the becameInvalid callback, it doesn't get removed from the template. It just shows a blank entry.

When it is waiting for the server to load it is just showing the name, which is expected.

Ember Model code

App.Job = DS.Model.extend({
  name : DS.attr("string"),
  user : DS.belongsTo("App.User", {embedded : "load"}),
  plans : DS.hasMany("App.Plan", {embedded : "load"}),
  shares : DS.hasMany("App.Share", {embedded : "load"}),

  becameInvalid : function(data){
    this.deleteRecord();
  }
});

Ember controller call

PlanSource.Job.createRecord({"name" : name});
job.save();

Rails create method

def create
  if can? :create, Job
    @job = Job.new(name: params["job"]["name"], user_id: current_user.id)
    if [email protected]
      render :json => {job: @job}, status: :unprocessable_entity
      return
    end
    if
      render :json => {:job => @job}, include: [:plans, :user, :shares => {except:   :token, include: [:user, :job]}]
    else
      render_no_permission
    end
  else
    render_no_permission
  end
end

My question is what is the best way to handle server side validation errors. I don't want to try to resubmit the record, I just want to delete it. I was looking for something to make Ember wait for server response but found nothing.

This method isn't working because it causes undefined errors down the model pipeline after deleting.

1

1 Answers

2
votes

My question is what is the best way to handle server side validation errors.

Not sure there is one best way. Depends on what you want to happen in your UI. Typically you will want to let the user know that the record was not saved and present some information what went wrong.

I don't want to try to resubmit the record, I just want to delete it.

OK. If the record is new, delete does not really make sense but probably what you want to do is rollback the transaction? Try this.transaction.rollback() or this.rollback(). For example:

App.Job = DS.Model.extend({
  name : DS.attr("string"),
  user : DS.belongsTo("App.User", {embedded : "load"}),
  plans : DS.hasMany("App.Plan", {embedded : "load"}),
  shares : DS.hasMany("App.Share", {embedded : "load"}),

  becameInvalid : function(data){
    this.transaction.rollback();
  }
});

See: How to deleteRecord when it was never committed on the backend?

I was looking for something to make Ember wait for server response but found nothing.

model.save() returns a promise. That means you can add success/failure handlers like this:

PlanSource.Job.createRecord({"name" : name});
var success = function(model) {
  alert('ok');
};
var failure = function(model) {
  alert('fail');
};
job.save().then(success, failure);