Route page without ID - How to use another field?

103 Views Asked by At

I am trying to access a specific route with a specific field in my model.

Example: www.myPage.com/wedding/couple1 www.myPage.com/wedding/couple2

All examples that I found in Ember's community use ID, but I am trying to use another one (which I will make sure to be unique).

My route config:

Router.map(function() {
  this.route('create-wedding');
  this.route('weddings');
  this.route('wedding', { path: 'wedding/:pageName' });
});

My link to the route:

{{#link-to 'wedding' wedding.pageName}}Access{{/link-to}}

Try to get the record:

model(params) {
  return this.store.query('wedding', { orderBy: 'pageName', equalTo: params.pageName });
}

But, how to get the record for the specific param "pageName" in my Route model? And how to get the same record when the user access the page directly from the URL?

Thanks in advance

2

There are 2 best solutions below

6
On BEST ANSWER

If your non-id field is really, truly unique (i.e. enforced uniqueness on the back end), you can use it as your front end id by writing a custom serializer.

export default DS.JSONSerializer.extend({
  primaryKey: 'other_unique_key'
});

If you are using a REST back end, just swap out DS.JSONSerializer for DS.RESTSerializer in the code above.

This would allow you to closely follow Ember's conventions for record handling by id. You can read more about authoring custom serializers here in the Guides.

Another alternative is to use Query Parameters. In that case, your URL would look more like http://example.com/weddings?wedding=romeojuliet

Read more about Query Parameters and accessing their values here in the Guides.

0
On

More details can be found here. https://guides.emberjs.com/v2.15.0/models/finding-records/

For this line to work return this.store.query('wedding', { orderBy: 'pageName', equalTo: params.pageName });

You'll need to setup filters on your API that will utilize those params.

You can also serialize a new ID, or set up the API to consume a slug instead of an ID. In which case you could do a direct find like this. return this.get('store').findRecord('wedding', params.pageParam)

Technically you should use queryRecord instead of query in the case of a single record.

And if it is a single record, what is the purpose of orderBy?

And how do I get the same record when the user access the page directly from the URL?

Because you have this in your router. this.route('wedding', { path: 'wedding/:pageName' });

You are already setup to access it directly in your url as domainname/wedding/pagename