Search code examples
ruby-on-railsember.jsember-dataember-rails

Ember date belongTo with serialized id


App.Locale = DS.Model.extend
  language: DS.belongsTo("language")

App.LocaleSerializer = App.ApplicationSerializer.extend
   attrs:
     language:  { serialize: "id", deserialize: "records" }

Using ember with rails as the backend. I am trying to create a locale, which has a dropdown to select a language. My idea is to pass a language_id to the backend, however I get the following when I submit.

{"locale"=>{"language"=>"15" }

How do I convert this to look like

{"locale"=>{"language_id"=>"15" }

Thanks


Solution

  • Assuming that you're using the ActiveModelSerializer, I think your answer is here. Just add the key attribute to the hash:

    App.LocaleSerializer = App.ApplicationSerializer.extend
      attrs:
        language:  { key: "language_id", serialize: "id", deserialize: "records" }
    

    If you only want to use language_id when serializing, but get language when deserializing, you can always override serializeBelongsTo:

    App.LocaleSerializer = App.ApplicationSerializer.extend
      serializeBelongsTo: (record, json, relationship) ->
        if relationship.key is 'language'
          json.language_id = Ember.get record, 'language.id'
        else
          @_super record, json, relationship