2011-12-14 12 views
7

Rails有嵌套的资源一段时间,它已被大量使用(或过度使用)。假设我们有两个模型,文章和评论。SpineJS url()支持Rails中的嵌套资源吗?

class Article < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :article 
end 

定义嵌套的资源在routes.rb中

resources :articles do 
    resources :comments 
end 

所以,现在,我们可以列出具体条款的评论: http://localhost:3000/articles/1/comments

但脊柱只能使网址后请求创建文章和评论是这样的:

/articles 
/comments 

如何使Spine的Ajax请求的URL如此?

/articles/1/comments 

我知道我可以覆盖评论模型的URL()用于检索的意见,但有关创建一个新的记录呢?

我也经历了源代码,我发现的是,Spine的Ajax模块中的create()方法并不关心Comment的实例中的自定义url()函数。我想要的只是传递article_id并将其与我的自定义url()函数一起使用以生成url,然后我可以发布到服务器进行创建。

没有叉子和修改后的Spine版本可以吗?

顺便说一句:对不起,我的英语水平,希望所有的你们能理解我想说一下:-)

谢谢你和问候一下,

回答

2

模型的url属性可以是一个值或一个函数。所以,你可以这样做:

class Comment extends Spine.Model 
    @configure "comment", "article_id" 
    @extend Spine.Model.Ajax 

    @url: -> 
    "articles/#{article_id}/comments" 

或类似的东西。 ajax模块将评估此属性,并在构建请求时将其用作资源终点。

+0

正如丹尼尔在这个问题中所说,这不适用于创作。 – Pelle 2012-01-07 22:30:34

+0

由于Ajax.getURL函数传递了Comment模型而不是注释的实例,所以这对于创建URL不起作用。所以它不知道article_id是什么。检查我的答案:) – SpoBo 2012-02-15 15:58:59

0

我有同样的问题,因为这似乎是与脊柱最大的问题之一。

由于它的简单性,用BackBone实现起来相当简单,但是Spine的内部结构非常复杂,这使得它非常困难。

如果我有解决方案,我试图实施立场会回来。

2

添加

#= require spine/relation 

到应用程序/ JavaScript的/应用/视图/ index.js。COFEE

补充的关系扩展

class App.Project extends Spine.Model 
    @configure 'Project', 'name' 
    @extend Spine.Model.Ajax 
    @hasMany 'pages', 'projects/page' 

class App.Page extends Spine.Model 
    @configure 'Page', 'name', 'content' 
    @extend Spine.Model.Ajax 
    @belongsTo 'project', 'Project' 

在JavaScript控制台

App.Project.find(the_id).pages().create({name:"asd"}) 

更多信息在http://spinejs.com/docs/relations

链接是spinejs模型文档

2

我的底部有一个解决方案:

http://groups.google.com/group/spinejs/browse_thread/thread/6a5327cdb8afdc69?tvc=2

https://github.com/SpoBo/spine

我做它覆盖了如何URL的阿贾克斯模块中产生一个叉。这允许create url包含模型实例数据的一些位。例如:/ articles/1/comments。适用于创建,更新等。

class App.Post extends Spine.Model 
    @configure 'Post', 'channel_id', 'title' 
    @extend Spine.Model.Ajax 

    resourceUrl: -> 
    "channels/#{@channel_id}/posts" 

    @hasOne 'channel', 'App.Channel' 
0

以下代码为我工作,但然后它没有......(和我修改了这个答案)。所以这不是一个好的解决方案,因为Ajax请求是由Spine排队的。它始终适用于第一条评论,但不适用于后续调用,因为超级调用会在没有发送PUT/POST的情况下返回。

class Comment extends Spine.Model 
    @configure "comment", "article_id" 
    @extend Spine.Model.Ajax 

    # hack for nested: @article_id is only set correctly during save 
    @article_id = "?" 
    @url: =>"/articles/#{@article_id}/comments" 

    save:()=> 
    # hack for nested resources (see @url) 
    Comment.article_id = @article_id 
    super 
    Comment.article_id = "?"