Join Justin Yost for an in-depth discussion in this video Find a record, part of Ember.js Essential Training.
- [Narrator] So now that we have the basics of retrieving a model and working with a collection of records, let's instead work with finding just a single record. We already know the route is where we handle finding and retrieving records, so let's add a page in which we're going to find a single record and display it on the screen. To begin, we need a route. So let's add a route using the pattern that we've already followed: ember g route bookmarks/about. And next, we need to open the corresponding router file in our text editor at app, routes, bookmarks, about.js.
And here, we need to build an Ember data query to find our record. Recall, we first need to add a model hook in our extend code block. So we'll add the model hook by doing model() on line four and adding in our curly braces. At this, we then need to add in a find. We have some different options for this ability. We add the basic option using the store to retrieve a record by an ID. That looks like this: return this.get('store').
From the store, we can then call the command findRecord, pass in the name of the model we wish to find, bookmark, and then the ID of the record, in this case one. If we save this, navigate in our browser to the bookmarks about page, and look in our data tab, we'll see that we have one bookmark returned for the bookmarks about page. That's part of the work. Let's see how else we can solve this problem. If we go back to our editor, we can write this in a slightly different manner to filter for a single record by using the method query record.
So if you need to query for a particular record, you can do so using this queryRecord pattern. In this specific case, I'm not going to worry about doing though this way. Instead, I want to focus just on the findRecord, so I'm going to go ahead and comment this out and we'll just leave it there in case we ever want to come back to this. Notice, when we go back to our about page, we still have just the single bookmark loaded. So we're able to very quickly and easily find a bookmark record by passing in a particular ID and returning that specific bookmark record.
- Why choose Ember?
- Installing Ember.js and Ember Inspector
- Defining the model
- Creating nested and dynamic routes
- Loading templates with routes
- Rendering different templates
- Displaying collections
- Working with Ember components
- Building forms
- Creating, editing, and deleting records
- Configuring Ember.js applications
- Testing your Ember application
- Installing add-ins
- Upgrading an Ember application