I have a Rails app using the ActiveModel Serializer gem and an Ember frontent. Until now I have been using the RESTAdapter and manually performing the renaming of keys in the models serializers. However, I just started working on persisting records to the backend, and I realized that I can’t use the RESTAdapter anymore. What happens is that the Rails controller permits only the book_id
and status
parameters, not the book
or user
. The RESTAdapter does not convert these automatically:
Started POST "/notes" for 127.0.0.1 at 2014-05-02 19:09:43 +0100
Processing by NotesController#create as JSON
Parameters: {"note"=>{"status"=>"to read", "book"=>"25", "user"=>nil}, "auth_token"=>"[FILTERED]"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = '[FILTERED]' LIMIT 1
Unpermitted parameters: book, user
(0.3ms) BEGIN
(0.3ms) ROLLBACK
Completed 422 Unprocessable Entity in 11ms (Views: 0.4ms | ActiveRecord: 1.3ms)
So I discovered the ActiveModelAdapter and added it to the app like this:
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({});
The adapter correctly maps the book
and book_id
parameters. The rails controller therefore accepts the request:
Started POST "/notes" for 127.0.0.1 at 2014-05-02 19:14:42 +0100
Processing by NotesController#create as JSON
Parameters: {"note"=>{"status"=>"to read", "book_id"=>"25", "user_id"=>nil}, "auth_token"=>"[FILTERED]"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = '[FILTERED]' LIMIT 1
Unpermitted parameters: user_id
(0.3ms) BEGIN
SQL (0.5ms) INSERT INTO "notes" ("book_id", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["book_id", 25], ["created_at", "2014-05-02 18:14:42.961100"], ["updated_at", "2014-05-02 18:14:42.961100"], ["user_id", 1]]
(21.2ms) COMMIT
[...]
Completed 201 Created in 48ms (Views: 7.2ms | ActiveRecord: 23.6ms)
So this works well, but after changing the adapter, the relationships are no longer loaded into the store correctly. None of the relationships defined in the models work.
This is an example of the json with a book-belongsTo-author relationship, which fails to be loaded into the Ember store.
{
"authors": [
{
"id": 2,
"name": "Pam Conrad"
}
],
"books": [
{
"id": 2,
"title": "Pedro's Journal: A Voyage with Christopher Columbus, August 3, 1492-February 14, 1493",
"author": 2
}
]
}
Ember version:
DEBUG: ------------------------------- dependencies.js:6630
DEBUG: Ember : 1.7.0-beta.1+canary.d02aa7f4 dependencies.js:6630
DEBUG: Ember Data : 1.0.0-beta.7+canary.20adb1d5 dependencies.js:6630
DEBUG: Handlebars : 1.3.0 dependencies.js:6630
DEBUG: jQuery : 2.1.0 dependencies.js:6630
DEBUG: -------------------------------