Update foreign key naming conventions - fixes #158 #169

Merged
merged 1 commit into from Dec 22, 2012

4 participants

@dgeb

This pull request addresses the issues raised by @tchak in #158:

  • It appends an _id (or _ids) suffix to associations' keys when embedding ids. This brings AMS more in line with API conventions and the expectations of Ember Data. The name of the key can still be overridden with the key option.

  • When objects are embedded in the root, they are now named according to their serializer, instead of the key used for their associations. This can still be overridden with the root option.

Note: This PR will bring Ember Data closer to working out-of-the-box with AMS. However, Ember Data will still need to be updated to recognize the _ids suffix for HasMany associations.

@tchak

Shouldn't it be optional?

@ahawkins

This could be set if objects aren't embedded.

@dgeb

@twinturbo The _id / _ids suffixes are only appended to keys when embedding ids, not objects.

For example, when embedding ids, keys such as author_id and comment_ids will be used:

{
  "post": {
    "id": 1,
    "title": "New post",
    "body": "A body!",
    "author_id": 123,
    "comment_ids": [ 1, 2 ]
  },
  "comments": [
    { "id": 1, "body": "what a dumb post" },
    { "id": 2, "body": "i liked it" },
  ],
  "authors": [
    { "id": 123, "name": "Joseph Blow" },  
  ]
}

When embedding objects directly, keys such as author and comments will still be used:

{
  "post": {
    "id": 1,
    "title": "New post",
    "body": "A body!",
    "author": { "id": 123, "name": "Joseph Blow" },
    "comments": [
      { "id": 1, "body": "what a dumb post" },
      { "id": 2, "body": "i liked it" },
    ]
  }
}

I think these are more conventional and understandable defaults.

@ahawkins
@dgeb dgeb Append an `_id` or `_ids` suffix to associations' keys. Embed objects…
… in root according to their serializers' names.

An `_id` suffix will be appended to the name of HasOne associations, while `_ids` will be appended to the singularized name of HasMany associations. Association keys can still be overridden with the `key` option.

Furthermore, objects embedded in the root are now by default named according to their serializer, instead of the key used for their associations.
3b1d2fa
@steveklabnik steveklabnik merged commit 7f87c9b into rails-api:master Dec 22, 2012

1 check passed

Details default The Travis build passed
@steveklabnik

Hey, sorry this took me so long to merge. Looks good. :shipit: ❤️

@dgeb

@steveklabnik thanks much!

Now I'll get to work on a PR for ember-data so that the _ids suffix is recognized by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment