私はまさにこの問題の解決策を自分で探していました。モデル メソッドを変更して Rails でより適切に動作するようにすることについて、この記事の JavascriptMVC フォーラムでのトリッキーの提案に触発されて、独自の解決策を思いつきました。serialize()
彼の提案のように、Model クラスの独自の拡張機能を作成し、include
含めたい属性をリストできるフィールドをモデルに追加しました (Rails の as_json メソッドの後にパターン化)。
can.Model("BaseModel", {}, {
serialize: function() {
var data, retval, serialized;
data = {};
retval = {};
serialized = can.Model.prototype.serialize.call(this);
//check if we're using the "include" fields or not
if (typeof this.constructor.include !== 'undefined') {
can.each(this.constructor.include, function(attr) {
data[attr] = serialized[attr];
});
} else {
data = serialized;
}
//wrap the return value in the model name for Rails purposes, e.g. {"event": {data}}
retval[this.constructor._shortName] = data;
return retval;
}
});
次に、モデルで「include」配列を使用して、含めたいフィールドを示します。"attendees" と "speakers" を省略すると、これらの関連モデルは、サーバーに送り返されるシリアル化された JSON にパッケージ化されません。
Event = BaseModel.extend('Event', {
findAll: "GET /admin/events",
findOne: "GET /admin/events/{id}",
create: "POST /admin/events",
update: "PUT /admin/events/{id}",
destroy: "DELETE /admin/events/{id}",
attributes: {
attendees: 'Models.User.models',
speakers: 'Models.User.models'
},
include: ['id', 'name', 'start_time', 'end_time']
}, {});