Know how to CRUD

While there are some similarities to Rails, there a few differences to keep in mind when performing CRUD operations in Ember. Let’s compare creating, updating and deleting a user in both frameworks.

Creating a new User instance:

In Rails:  app/controllers/users_controller.rb:

Screen Shot 2015-11-24 at 8.26.16 PM

In Ember:  # app/routes/users/new.js:

Screen Shot 2015-11-24 at 8.27.47 PM

In both cases, we create a new instance of a User, but do not persist it. Persisting records to the database (or API) has some differences. In Rails we add a create action, create a new instance based on parameters that were passed, and then call save on it.

In Ember, we only need to add an action to our users/new route that saves the User record we’re currently working with.

In Rails: # app/controllers/users_controller.rb:

Screen Shot 2015-11-24 at 8.32.32 PM

In Ember: #app/routes/users/new.js:

Screen Shot 2015-11-24 at 8.34.11 PM

Updating user attributes:

user.setProperties({ firstName: ‘Tatsiana’, lastName: ‘Borshch’ });

One key difference between Rails update_attributes and Ember setProperties is that update_attributes will automatically persist the record to the database, while setProperties  will update the record immediately on the client but not attempt to save it. We can verify this by checking the isDirty property, which is equivalent to the changed? method in Rails. To actually save the record in Ember, we need to call save. Ember will make a PUT request to the API to persist the changes.

Deleting a user:

To delete a record in Rails the destroy method is used. In Ember, the equivalent function is destroyRecord, which marks a record as deleted and immediately calls save on it. In case the destroy fails, it is a good idea to use catch along with reload to refresh the state of the model from the server.

Screen Shot 2015-11-24 at 8.51.40 PM

Ember models also have a function called deleteRecord. Like destroyRecord, the record will be marked as deleted. The difference is that save will not be called afterwards.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s