简体   繁体   中英

Ember.js / Rails Posting Relationships to Rails

Ok, I'm working on a simple Ember / Rails app, and I'm trying to post a hasMany association in a single HTTP request. For what it's worth, I'm using Rails for the API.

  • Ember: 1.4.0-beta.1+canary.011b67b8

  • Ember Data: 1.0.0-beta.5+canary.d9ce2a53

  • Handlebars: 1.1.1

  • jQuery: 1.10.2

Release Model

App.Release = DS.Model.extend
  name: DS.attr 'string'
  tracks: DS.hasMany 'track', {embedded: 'true'}

A "Release" has many "Tracks"

App.ReleasesNewRoute = Ember.Route.extend

  model: -> @store.createRecord 'release'

  afterModel: (release, transition)->
    release.get('tracks').addObject(@store.createRecord 'track',{
      name: 'Track 1'  
    }).pushObject(@store.createRecord 'track',{
      name: 'Track 2'  
    })

  setupController: (controller, model)->
    controller.set('content', model)

Releases Controller

App.ReleasesNewController = Ember.ObjectController.extend

  actions:{
    save: ->
      @content.save()
  }

How can I post the two tracks and one release at once? I'm planning to use accepts_nested_attributes_for :tracks in my Rails API... but I'll be happy if I can see the Tracks in my development console for a start.

I got this working like this:

App.ReleaseSerializer = DS.RESTSerializer.extend

  serializeHasMany: (record, json, relationship)->  
    key = relationship.key
    hasManyRecords = Ember.get(record, key)

    key = key+'_attributes'

    if hasManyRecords && relationship.options.embedded == 'true'
      json[key] = []
      hasManyRecords.forEach (item, index)->
        json[key].push(item.serialize())
    else
      @._super(record, json, relationship)

This works nicely with :accepts_nested_attributes_for in Rails. Rails is expecting a hash of track models nested under the release as tracks_attributes .

Couple gotchas:

  • Rails won't use the create action for the Child model, you'll have to put anything you wanna do to the children models in your Parent's create action.

  • Remember to whitelist your children's parameters for Rails 4. This looks like:

      def release_params params.require(:release).permit(:name, tracks_attributes: [:name]) end 

'embedded' is not supported anymore in ember-data 1 beta. check this link to see how to create child records with using embed. Better to use

https://github.com/emberjs/data/blob/master/TRANSITION.md#embedded-records

check this question to know more about creating child records in a different and better way How to Add Child Record to Existing Parent Record?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM