dimanche 19 juillet 2020

Handling validation errors in ember and rails

Recently, I switched to using ember as my frontend framework from react. I am saving tons of time writing ember although I am new at ember. Like in every app, validation errors needs to be addressed and I'm having a tough time. I have read multiple articles still some parts don't click and hence this question.

I have a rails backend API server that renders API in json api format as expected by ember. The errors are rendered like:

{
  "errors": [
    {
      "detail": "Title can't be blank",
      "source": {
        "pointer": "data/attributes/title"
      }
    }
  ]
}

I have a ember controller with all the logic and I'm not sure if this is the right place to submit forms etc

// controllers/categories/new.js

export default class CategoriesNewController extends Controller {
  @service store;

  @tracked title = "";
  @tracked description = "";
  @tracked errors = [];

  @action submitData(e) {
    e.preventDefault();
    let category = this.store.createRecord("category", {
      title: this.title,
      description: this.description,
    });

    let self = this;

    category.save().then(
      () => {
        self.transitionToRoute("categories");
      },
      () => {
        self.errors = category.errors.get("title");
      }
    );
  }
}

and an ember template file like

# templates/html/new.hbs

   <p class="mt-1 text-sm font-medium text-red-700">
      
   </p>

This is only the error handling part. I'm sure this is not the correct way to handle validation errors. This article handles error on the model file and I'm not sure how? Can anyone please guide me? Thanks.

PS: I am using ember-cli 3.19.0.




Aucun commentaire:

Enregistrer un commentaire