Skip to content

Instantly share code, notes, and snippets.

@boy-jer
Forked from darthdeus/0_intro.md
Created April 24, 2013 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boy-jer/5455138 to your computer and use it in GitHub Desktop.
Save boy-jer/5455138 to your computer and use it in GitHub Desktop.

I've been trying to do routing in Ember using something other than id. This is how I implemted a dasherized version of a post's title. I get the feeling that instead of the deserialize function I should be overwrite the model function as the guides suggest, but then I lose the symmetry I have with the serialize function.

If there's a better/more ember way, I'd love to know.

Thanks @darthdeus for teaching me about DS.LoadPromise

The DS Model

App.Post = DS.Model.extend
  title: DS.attr('string')

  slug: (->
    Em.String.dasherize @get('title')
  ).property('title')

The Router

App.Router = Ember.Router.extend()

App.Router.map (match) ->
  match('/posts/:post_slug').to "post"

App.PostRoute = Ember.Route.extend

  serialize: (model, params) ->
    object = {}
    name = params[0]
    object[name] = model.get('slug')
    return object

  deserialize: (params) ->
    slug = params['post_slug']
    title = slug.split('-').join(' ')
    posts = App.Post.find({title: title})
    
    posts.one "didLoad", ->
      posts.resolve(posts.get("firstObject"))

    @currentModel = posts

We have to make sure the query is case insensitive.

class PostsController < ApplicationController
  respond_to :json
  def index
    @posts = params[:title] ? Post.find_by_title(params[:title]) : Post.all
    render json: @posts
  end
end

class Post < ActiveRecord::Base
  attr_accessible :body, :title

  def self.find_by_title(title)
    Post.where("lower(title) = lower(:title)", :title => title)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment