How do I access the URL that Ember Data will PUT to? - ember.js

I'm adapting an old JS (no framework) + Rails app as an Ember learning exercise. The idea of the application is that I'm producing a pdf from some data input. In the initial version, there was no user persistence - you could modify the data provided to you in the tables, and then download the PDF of it.
As part of this, I decided to run with a decidedly non-standard ember framework - I'm essentially using Ember Data to load the initial value of the tables. Ember has been a really natural fit for the models I have on the Rails side, and it's made a lot of the more complicated calculations a lot easier. The issue I have is that my initial idea was that when I came to download the PDF, I'd respond to the "save" action on Ember Data with binary data (with an application/pdf header), which I could then use something like FileSaver.js to serve up to the client. Then, I found that EmberData needs JSON return value.
So I base64 encoded my PDF response and fired it back..but it didn't fit the model schema. I thought I'd then do a manual AJAX save -
CalculateYourTV.RostersShowController = Ember.ObjectController.extend({
actions:{
download: function(){
var roster = this.get("model");
var team = roster.get('team');
return this.ajax('*URL GOES HERE*', record.toJSON(), "PUT").then(function(data) {
console.log('called')
console.log(data)
});
},
}
})
And this is where I'm currently stuck. Is there any way to access the URL that EmberData is posting to? I could hard-code a route in the Rails side of things, but I don't like hardcoding routes in here, and I'd like to keep it as reusable as possible (I'm planning to eventually allow data persistance).

Just open chrome dev tools (or firebug) and monitor what's going on in the network tab. You should see any ajax request your application sends out, including the EmberData's save request.

You can change the URL that a specific model will hit by creating custom Ember Data adapters per model.
For example, say you have a person model that needs to not hit the default /persons URL.
App.PersonAdapter = App.ApplicationAdapter.extend({
pathForType: 'special/custom/endpoint/for/folks'
});
That said, Ember Data may not be the best tool here for your PDF "model". You can always use Ember Data for the majority of your models, but use a quick $.ajax for other stuff that doesn't fit your definition of a true model.

You can ask the adapter to build a URL for you -
adapter = #store.adapterFor('application')
url = adapter.buildURL(type, id)
where type is the name of the model, and id is its id.
If want to look up the adapter directly in the container it is
#container.lookup('adapter:application')

Related

preventing a duplicate request in Ember Data when trying to set the route model to the result of an association

I have a route where I need to fetch associated data that is not available in the parent routes, so I need to basically reload the model and in the process provide JSONAPI with the include directive to embed other models. So the route looks like this.
import Ember from 'ember';
// route for patients/1/appointments
export default Ember.Route.extend({
model: function() {
const query = {
id: this.modelFor('patient').get('id'),
include: 'appointments,appointments.practitioner'
},
success = function(patient) {
return patient.get('appointments');
};
return this.store.queryRecord('patient', query).then(success);
}
});
The success callback is fetching the appointments a second time, which maybe isn't surprising, but it should seemingly also know that it has those in the store locally. So, I'm trying to resolve a reasonable way to set the model to the set of appointment models coming back. For various reasons, we don't want the logic of this specific request to live in the adapters, since (for example) we may not always need the practitioner side loaded anytime we get the patient's appointments. Any ideas?
I think that there must be some issue with your response from server after first queryRecord.
I created simple Ember Twiddle that matches your example and is based on mockjax here. As you can see when you open Console, the mockjax is getting only two requests - first for /patient/1 and second for /patients?... (your queryRecord).
Even though I am rendering all appointments that are relationship to current patient, mockjax does not get any other query for relationships. You can check out the JSON responses I provided for mockjax. You should compare them with your API to see if there are different in structure.

Url not updating when new model is saved

router.js
this.route('claim', function() {
this.route('new');
this.route('edit', { path: '/:claim_id' });
});
claim.new -> redirect to claim.edit with an empty model. this.transitionTo('claim.edit', model);
Initially, because the model is not saved we get: index.html#/claim/null
When we save the model, it continues to display as index.html#/claim/null instead of say index.html#/claim/87
Is there a way to force the url to refresh?
The only way to force the URL to refresh is to force the route/page to refresh. You can use the refresh method in your route to do that.
To understand why it doesn't update automatically, you have to understand how routes work and how Ember is separate from Ember Data (or any data persistence library).
First, you have to remember that Ember has no knowledge of Ember Data and the specifics of its object model. It just sees plain Ember objects. Ember Data models are more important than other models to you, but Ember isn't aware of that distinction.
Second, the routing in Ember is binding/observer aware. It doesn't watch for changes and update URL state accordingly. It calculates the URL once using the serializer hook, then it leaves it as that. It's not going to recalculate if your model changes in any way. It will only recalculate when it's refreshed.
Short story long, the part of your application that changes the ID of your model and the part that calculates the URL to use aren't aware of each other. You'll have to manually sync them up. Using the refresh method is probably easiest way to do that.
UPDATE: As Kitler pointed out, you can also transition to your route using the new model. It won't fire the model hook so it won't have to do any asynchronous work, but it will still update the URL.

Ember CLI path based on server response

I'm developing a substantial ember app, using Ember CLI, and I'm struggling with a few aspects of it.
What I want to do is:
Show a dropdown list of options
When the user picks an option, post their choice to the backend
The response from the server contains data based on what the user picked in the dropdown. After getting the server response I want to transition to a new route where the path ends with one of the values returned by the server.
For example:
/path/to/dropdown -- shows the dropdown for the user to pick from, which is then POSTed to the backend. The backend responds with, amongst other data:
slug: <stringValue>
This then transitions to:
/path/to/slug -- where slug is <stringValue>
So far I've got 1 & 2 above working, but I can't figure out how to make step 3 work. I've tried using a serialize function in the /path/to/slug route and the /path/to/dropdown controller, but it always returns undefined.
The AJAX call to the server, based on the user's dropdown choice, happens in the /path/to/dropdown controller.
I've set up the router as:
this.route('options', { path : ':slug' });
Would be great if someone could point me in the right direction; I hope my example is clear enough but let me know if not.
Thanks.
To be honest I don't understand why do you use this.route('options', { path : ':slug' });. You just created the only route for all possible options (in fact, for all urls of form /anything), but that's not what you want.
I think your solution is this.transitionToRoute(url_string) which is available in any controller. Check the api example there. But before you should declare all that routes in the router and create operating files for them, of course.
If you don't want to create a route for each possible slug, so then your route is pretty excellent, but at least I'd consider to add one more path section. For example, this.route('options', { path : '/slugs/:slug' });.
After that you can run transitionTo and pass data (in any format) to it. The data will be assigned to the route model and you will be able to use it in the SlugRoute (and SlugController, if you didn't redefined the setupControler method) as a this.get('model') variable.
If you want to run transition from the view, firstly you need to obtain the controller and send a special command to it.

Custom Ember Api Endpoint

I am trying to figure out how to get data from a custom api. I am using Ember 1.8.1, Ember Data 1.0.0-beta.12 and Ember CLI
In my router i have the following resource
this.resource("communities", {path: '/communities/:community-id/follow-ups'}, function() {});
I have my model defined for the correct response. In my communities router I am trying to get the data from the api like so
this.store.find('community', params['community-id']);
The problem I am having is that I am trying to retrive data from the api endpoint
/communities/{community-id}/follow-ups
But the app is trying to grab the data from
/communities/{community-id}
How do I define the custom resource route to pull from the follow-ups
The router path isn't going to change where the API makes the call to, that just helps Ember change the browser path.
You might want to consider using an adapter if you really need it to hit .../follow-ups.
You'd want to make a CommunitiesAdapter I think. ember g adapter communities, or community, not sure offhand.
And I think the function on it you're looking for is pathForType.
Check it out at http://guides.emberjs.com/v1.10.0/models/customizing-adapters/
You can create a custom adapter for your model in particular but deep nesting on routes can be tricky in Ember and not worth the time if you are in a rush.
Try setting the model of the route directly with a get json
App.NAMERoute = Ember.Route.extend({
model : function(params){
return Ember.$.getJSON(window.apiHost+'/communities/'+params.group_id+'/follow-ups');
}
});
Sometimes simple solutions is what you need

Django Rest/Ember How to connect to models

I am getting started with Ember, and Django Rest Framework and I can't seem to peice together how to connect a model so that Ember can use the data in that model and create a simple drop down box. I have one model that I am starting with that is as such:
id
name
security
status
All I want to achieve is allowing Ember to use the data in this model and create a dropdown like so.
<select id="model">
<option value="model.ID">model.Name</option>
</select>
Can anyone help me with this? I am complete new to Ember and Django Rest.
Without going into a ton of detail, I've created a mini example of what you're looking for
http://emberjs.jsbin.com/Ozimatuj/2/edit
You'll note that I'm using mockjax, so instead of hitting any real endpoint, it's all mocked. Additionally I'd recommend using a client side record management solution (such as ember-data or ember-model). That's another discussion though.
In the application route (which correlates with the root of your app) it hits the model hook (which should return the model associated with that route. I'm returning a POJO of the users. That model is being assigned as the content of the application controller (automatically generated). The the application template is being built, and it's being backed by the application controller. Inside the application template we create an instance of ember select, and we tell it that the content backing it is model (which is the model/content in the application controller). We also say, use bind the user model (you could do id) and the name to the value and the label respectively.
I then bound the value of the select to selectedPerson, so anytime the value changes, the selectedPerson updates, the template which talks about that person will update. Magic. Ember does the rest.
This is a really broad question, so if you have any other questions, please ask a specific question, and I'd really recommend going through the getting started guide, it's really short, but will give you a decent foundation of terminology and methodology of Ember. http://emberjs.com/guides/getting-started/
For Ember Data I'd do a quick read the of the transition document for ED 1.0 beta.
https://github.com/emberjs/data/blob/master/TRANSITION.md
DS.DjangoRESTSerializer = DS.RESTSerializer.extend();
DS.DjangoRESTAdapter = DS.RESTAdapter.extend({
defaultSerializer: "DS/djangoREST"
});