与Rails资源的主干同步

时间:2013-01-08 23:17:00

标签: ruby-on-rails backbone.js

这是一个很长的问题,关于通过Backbone在Rails应用程序中创建数据库条目。我对如何处理Rails控制器中的数据以及如何设置骨干网中的URL有疑问。

我在rails中创建了一个带有标题,文本和关键字列的文档表,让Rails自动创建id列。我试图在控制台中创建两个文件,d7和d8。

在d7中,我尝试手动设置id和标题。当我试图“保存”它时,它给了我一个500错误。

在第8天,我制作了一个只有标题的文件。当我试图保存它时,它给了我404错误。

使用手动设置的ID和标题

创建doc(d7)
d7 = new Doc({ id: '007', title: 'Document 7'})
Doc Constructor french2.js:24
child

尝试保存d7会产生500错误

d7.save({}, { success : function(rec) {console.log('saved : ', rec); } })

    PUT http://localhost:3000/docs/007 500 (Internal Server Error) jquery.js:8215
    XHR finished loading: "http://localhost:3000/docs/007". jquery.js:8215
    Object {readyState: 4, responseText: "<!DOCTYPE html>↵<html lang="en">↵<head>↵  <meta ch…ders</b>: <pre>None</pre></p>↵↵↵↵</body>↵</html>↵", status: 500, statusText: "Internal Server Error"}

它还在DocsController中添加了“NoMethodError #refate undefined method'stringify_keys'

创建一个只有标题,没有id的文档(d8)(Rails手动设置id)

d8 = new Doc({title: 'Document 8'})
Doc Constructor french2.js:24
child

尝试在没有手动设置ID的情况下保存文档会产生404错误

Object
POST http://localhost:3000/docs/undefined 404 (Not Found) jquery.js:8215
XHR finished loading: "http://localhost:3000/docs/undefined". jquery.js:8215
Object {readyState: 4, responseText: "<!DOCTYPE html>↵<html lang="en">↵<head>↵  <meta ch…ation on available routes.↵</p>↵↵</body>↵</html>↵", status: 404, statusText: "Not Found"}

4个问题:

1)是否在Backbone Doc模型中正确设置了URL以便使用Rails资源。 this.url = "docs/" + this.id请参阅下面的doc模型以获取完整代码。

2)我是否应该调用保存d7.save()来创建文档?我注意到它在Rails docs控制器中触发了更新操作?

3)如何在不收到stringify键错误的情况下保存字符串?

4)Rails控制器:我的docs表有3个字段(标题,关键字,文本)以及任何rails添加它。我是否必须通过params中的列名明确标识每个字段(即params [:title] [:keywords]),或者下面的代码(我从别人那里复制)是正确的,其中只指定了symbol:doc ?该参数的名称是否随意?

     def create
        respond_with Doc.create(params[:doc])
     end 
     def update
       respond_with Doc.create(params[:id], params[:doc])
     end 

代码

将网址设置为this.url = "docs/" + this.id

的部分模型代码
  window.Doc = Backbone.Model.extend({

        initialize : function Doc() {

          this.url = "docs/" + this.id   #not sure if this is correct

            this.bind("error", function(model, error){
                console.log( error );
            });

        },

将网址设置为“docs”的集合

window.Docs = Backbone.Collection.extend({
            model : Doc,

            url: "docs",


            initialize : function() {
                console.log('Docs collection Constructor');
            }
        });

Rails doc控制器

class DocsController < ApplicationController

  respond_to :json

    def index
        respond_with Doc.all
    end 

    def show
        respond_with Doc.find(params[:id])

    end 

    def create
        respond_with Doc.create(params[:doc])
    end 

    def update
        respond_with Doc.create(params[:id], params[:doc])
    end 

    def destroy
        respond_with Doc
    end    

end

docs表

class CreateDocs < ActiveRecord::Migration
  def change
    create_table :docs do |t|
      t.string :title
      t.string :text
      t.string :keywords

      t.timestamps
    end
  end
end

创建了一些种子数据,但只设置了标题。 Rails会自动设置id,但是我可以手动设置吗?

Doc.create!(title: "doc 1")
Doc.create!(title: "doc 2")

1 个答案:

答案 0 :(得分:0)

对于模型上的url属性,为了直接保存在模型上(而不是通过Collection.create),您必须检查它是新条目还是更新。此代码对url属性执行此操作,并允许您为create和update调用obj.save()。

 url : function() {
  var base = 'documents';
  if (this.isNew()) return base;
  return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
}

对于Rails控制器,只需执行此操作

即可
def create
    respond_with Document.create(params[:doc])
end