-2

さて、最初のBackbone JSアプリをライブでプッシュしましたが、新しい問題が発生しました。どうやら、コメントやレビューのためにモデルを最初にロードしたとき、それらには、追加されたときのタイムスタンプを含む「created_at」属性があります。コメントを編集してからmodel.sync()を実行すると、「created_at」がサーバーに返されます。RoRアプリがそれについてつまずき、Rails開発者が私に言っているように、私はいかなる状況でも「created_at」をサーバーに戻すことはできず、表示のみのために計算されます。

今、何かが与えなければなりません。sync()の前にバックボーンをハックしていくつかの属性を削除するか、Rails側で何かを行う必要があります。

ソルトンについてのあなたの提案は何ですか?

そして、いずれにせよ、model.sync()中にいくつかの属性を渡さないために何ができるでしょうか?よろしくお願いします。

4

2 に答える 2

1

不変のプロパティに投稿しようとすると、この正確な問題が発生しました。バックボーンモデルの問題は、デフォルトでは、すべてまたは何も投稿しないことです。ただし、部分的な更新を行うことはできます。これに対処するために、Backbone.Modelの子孫を作成し、model.saveを次のようにオーバーライドしました。

    save : function(key, value, options) {
        var attributes, opts;

        //Need to use the same conditional that Backbone is using
        //in its default save so that attributes and options
        //are properly passed on to the prototype
        if (_.isObject(key) || key == null) {
            attributes = key;
            opts = value;
        } else {
            attributes = {};
            attributes[key] = value;
            opts = options;
        }

        //Now check to see if a partial update was requested
        //If so, then copy the passed attributes into options.data.
        //This will be passed through to Backbone.sync. When sync
        //sees that there's an options.data member, it'll use it instead of
        //the standard attributes hash.
        if (opts && opts.partialUpdate) {
            opts["data"] = JSON.stringify(attributes);
            opts["contentType"] = "application/json";
        }

        //Finally, make a call to the default save now that we've
        //got all the details worked out.
        return Backbone.Model.prototype.save.call(this, attributes, opts);
    }

これにより、次のように、必要な属性をバックエンドに選択的に投稿できます。

//from the view - the GET may have delivered 20 fields to me, but I'm only interested
//in posting the two fields.
this.model.save({
    field1 : field1Value,
    field2 : field2Value
},{
       partialUpdate : true
});

これが私の人生をとても楽にしてくれた方法をあなたに言うことはできません!それを考えると、changedAttributes()JSONを渡さない理由を尋ねる人もいるかもしれません。その理由は、場合によっては、変更された属性がクライアント側のみを対象としており、特にそのモデルも使用するビューへの変更を引き出すためです。

いずれにせよ、これを試してみてください...

于 2012-05-24T17:23:36.767 に答える
1

モデルに次を追加できます。

attr_protected :created_at, :updated_at
于 2012-05-24T17:28:06.270 に答える