告诉ember.js为其模型的“id”使用不同的键 [英] Tell ember.js to use different key for its model's "id"
问题描述
我陷入了一个情况,我不应该返回API端点中的 id
字段。我需要告诉ember使用 slug
字段为/而不是 id
。
I am stuck in a situation where I shouldn't return id
field in the API endpoint. I need to tell ember to use slug
field for / instead of id
.
我试过 DS.RESTAdapter.map('App.Post',id:{key:'slug'})
。虽然这对于 App.Post.find(a-slug-name)
完美无缺,但它混淆了 App.Post.find( )
导致在每次调用时添加新模型。并且还将 id
分配给null。
I tried DS.RESTAdapter.map('App.Post', id: {key: 'slug'})
. While this works perfectly fine for App.Post.find("a-slug-name")
, It messes up for App.Post.find()
resulting in adding a new model every time it is called. And also assigning id
to null.
那么该怎么做?
推荐答案
在适配器中指定应该用作 primaryKey
的属性。如果您希望 slug
属性作为您的发布
模型 id
,在您的适配器上定义 primaryKey
,如下所示:
You need to specify the attribute that should be used as the primaryKey
in your Adapter. If you want the slug
property to serve as your Post
model id
, define the primaryKey
on your Adapter like this:
DS.RESTAdapter.map('App.Post', {
primaryKey: 'slug'
});
更新
自Ember数据 1.0.0-beta.7 canary
,您需要执行此操作而不是上述代码段:
Update
As of Ember-data version 1.0.0-beta.7 canary
, you need to do this instead of the above snippet:
App.PostSerializer = DS.JSONSerializer.extend({
primaryKey: 'slug'
});
这篇关于告诉ember.js为其模型的“id”使用不同的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!