Passing multiple parameters to a route


#1

how can I pass multiple ID’s to a single route?

like http://localhost:4200/posts/5/6 or http://localhost:4200/posts/?id1=5&id2=6


#2

There are a lot of different things you could be asking here, but I’m going to assume you are trying to have multiple resources on one page, in which case you could do:

posts?filter[id]=1&filter[id]=2

by

 // GET to /posts?filter[id]=1&filter[id]=2
 this.store.query('post', {
   filter: {
     id: [1,2]
   }
}).then(function(posts) {
  // Do something with `posts`
});

https://guides.emberjs.com/release/models/finding-records/


#3

Both of your examples work fine and which one you’d want to use depends mostly on your use case.

For this version http://localhost:4200/posts/5/6 you could simply define your route with multiple dynamic segments (make sure you give each param a unique name!). This version would make sense if you had a small (known) number of ids to pass, if the UI would be nested at all or if they were related somehow, and/or if you like that URL structure more.

For the other version, http://localhost:4200/posts/?id1=5&id2=6, you just need to make sure you set your query params up in the route and ensure the refreshModel flag is set to true (assuming you want to refresh the model when they change). Then, as @zachly demonstrated, you could just pass these params straight into a query in your model hook. This would make sense if you had a larger number of items, or perhaps your view was more of a “queryable dataset” type of view.


#4

In this situation I often use one queryParam that expects a comma separated list of ids.

http://localhost:4200/posts/?ids=5,6

Then in the route’s model hook I split the queryParam into an array

export default Route.extend({
  queryParams: {
    ids: { refreshModel: true }
  },

  model(params) {
    ids = params.ids.split(',');
    return this.store.query('post', {
      filter: { id: ids }
    });
  }
});

#5

I will take a different interpretation then the other replies. I will assume you want multiple (different) models for a particular route.

Say you have this route setup:

this.route('posts', function() {
  this.route('show', { path: ':post_id' }, function() {
    this.route('sub-resource', { path: ':sub_resource_id' });
  });
});

Then you can build the hierarchy as such—

posts/show/route.js

import Route from '@ember/routing/route';

export default Route.extend({
  model(params) {
    return this.store.findRecord('post', params['post_id']);
  }
});

posts/show/sub-resource/route.js

import Route from '@ember/routing/route';
import { hash } from 'rsvp';

export default Route.extend({
  model(params) {
    return hash({
      post: this.modelFor('posts.show'),
      subResource: this.store.findRecord('sub-resource', params['sub_resource_id'])
    });
  }
});

Hope that helps.