1
votes

i'm a newbie in ember, and i've been scratching my head on this since yesterday. I want to make a simple Blog example using ember and rails with serializers.

I've been able to make the CRUD for posts, no problem. Most of the code is in the router.

I have a problem with my comments which are declared like that :

App.Comment = DS.Model.extend
   body: DS.attr('string')
   post: DS.belongsTo('App.Post')  

App.Post = DS.Model.extend
    title: DS.attr('string')
    body: DS.attr('string')
    comments: DS.hasMany('App.Comment',embedded: true)    

Displaying the comments of a post is ok, route looks like : /#/posts/:id/comments .

New comment link is on the bottom of the comments'list, so route for creating a new comment is :

/#/posts/:id/comments/new

At that point i hit the problem : how do i tell ember-data which post owns that comment ? I mean whart is the best practice for doing it ?

Finally i decided to initialize comment.post_id before displaying the form, coding it in the router. It looks like :

create: Em.Route.extend
   route: '/new'
   connectOutlets: (router, context) ->
      transaction = router.get('store').transaction()
      comment = transaction.createRecord(App.Comment)
      comment.set('post_id', router.get('postController').get('id'))
      router.get('applicationController').set('transaction', transaction)
      router.get('commentsController').connectOutlet
          viewClass: App.EditCommentView
          controller: router.get('commentController')
          context: comment
   save: (router, event) ->
       router.get('applicationController.transaction').commit()
       router.transitionTo('index')

But it doesn't work, coming back to the server, the post request has no value for post_id.

I tried to add an input field for post_id in the form to check the value before saving and the value is there and correct.

I tried to debug the save function in the router which is fired when the form is submitted. Here too the post_id value is correct.

I must be missing something but hell i don't know what .....

Philippe

1

1 Answers

1
votes

You should be setting the post on the comment, but not via the post_id property.

Yes, post_id is how both your server and Ember Data will serialize the association's foreign key, but that's a detail Ember Data wants to abstract away from you. When interacting with your models, you shouldn't know or care about how association data (or any data, really) is serialized by Ember Data and passed to the server. (In fact, unlike Rails, post_id will never actually exist as a property on your Comment records.)

Instead, you should simply interact with the attributes and associations as defined in your models. If you have a Comment model with a post belongsTo association, then just use comment.set('post', post). It's meant to behave like comment.post = post in Rails, taking care of all the details for you.