Pretty URL's with Active Model Serializers and Ember.js

Creating pretty URL's is a common question and in plain Rails apps it's pretty straight forward.

Instead of having a URL like we want a pretty, human friendly URL like where that last part is usually called a slug.

There are some awesome gems to do the slug-creating for you, like Friendly ID. But a simple way to get started is to append something like the title property to your objects' id and make it URL friendly:

class Post < ActiveRecord::Base  
  def to_param
    "#{id} #{title}".parameterize

This is actually all you need to do in a plain Rails app, and your posts will be accessible like: Awesome!

But how do I use this in my Ember project?

- you

Great question! We can actually do this by just telling our Serializers to use this method as the ID:

class PostSerializer < ActiveModel::Serializer  
  attributes :id, :title, :body

  def id

If you have any related objects, you'll need to make sure they use this property as the ID as well:

class CommentSerializer < ActiveModel::Serializer  
  attributes :id, :message
  has_one :post, embed: :id, embed_key: :to_param

The nice thing about this approach is that your models are still being found by id in you rails controllers (#find will #to_i your id so it always grabs the first number and strips off the rest) and you won't need to change any code to handle that.

That's it, now you have pretty, human friendly URL's in your Ember app!