jeudi 4 octobre 2018

Active Model Serializer with Ember - how to add an element to the collection

I have 2 models Country and Language linked with HABTM relation. I'm using Rails API with ActiveModelSerializer and Ember JS as frontend. So how is it possible to add a new language to country.languages collection ?

On the Ember side I'm trying to add a new language as follows:

#router

actions: {
saveLanguage(language) {
      let controller = this.get('controller');
      let country = controller.get('aCountry');
      country.get('languages').pushObject(language);
      country.save();
    }
}

This calls CountriesController#update action in Rails. Here is how I deserialize params hash in Rails controller:

#countries_controller.rb

    def country_params
      ActiveModelSerializers::Deserialization.jsonapi_parse!(params)
    end

And here is what it returns:

{:code=>"BE", :name=>"BELGIUM", :modified_by=>"XXX", :id=>"5", :language_ids=>["374", "231", "69"]}

So I'm getting all I need:

country ID => id=5
languages IDS => both existing ones (2) and a new one.

How to properly update the country ? Thank you.




Aucun commentaire:

Enregistrer un commentaire