SpineJS url()可以支持Rails中的嵌套资源吗?

时间:2011-12-14 14:05:25

标签: javascript ruby-on-rails ruby-on-rails-3 spine.js

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

但Spine只能为帖子请求创建文章和评论的网址:

/articles
/comments

如何为这样的Ajax请求制作Spine的url?

/articles/1/comments

我知道我可以覆盖评论模型中的url()以获取检索评论,但是如何创建新记录呢?

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

没有fork和Spine的修改版本可以自己吗?

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

谢谢你,最诚挚的问候,

5 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:2)

添加

#= require spine/relation

到app / javascript / app / views / 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 :(得分:2)

我有一个解决方案:

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

https://github.com/SpoBo/spine

我做了一个fork,它会覆盖在ajax模块中生成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' 

答案 3 :(得分:0)

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

使用BackBone实现它非常简单,因为它很简单,但是Spine的内部结构非常复杂,因此非常困难。

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

答案 4 :(得分:0)

以下代码为我工作但是它没有...(我修改了这个答案)。因此,这不是一个好的解决方案,因为Ajax请求由Spine排队。它始终适用于第一个注释,但不适用于后续调用,因为对super的调用将在没有发送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 = "?"
相关问题