简体   繁体   English

具有动态参数的骨干网收集网址

[英]Backbone Collection url with dynamic parameters

I'm writing a Rails app with Backbone.js. 我正在用Backbone.js编写Rails应用程序。

In Rails, I have a route in config/routes.rb that takes an argument like this: /api/u/foo . 在Rails中,我在config/routes.rb中有一条路由,接受这样的参数: /api/u/foo It gets all posts by the argument, in this case foo . 它通过参数获取所有帖子,在本例中为foo The output of this is all posts by foo. 此输出是foo的所有帖子。 Foo is a user, who has many posts. Foo是一位用户,拥有很多帖子。

In Backbone, I need to set the url attribute on the collection to take arguments from the route, like this: /u/foo . 在Backbone中,我需要在集合上设置url属性以从路由中获取参数,例如: /u/foo I want that to go get /api/u/foo.json . 我想去得到/api/u/foo.json How could I do this? 我该怎么办? I tried taking a user argument on the Backbone route, but I could't get it to the collection. 我尝试在Backbone路由上接受user参数,但无法将其传递给集合。

The relevant part of the routes.rb file: routes.rb文件的相关部分:

scope 'api' do
  get "/u/:user", :action => "index", :controller => "posts"
end

Assuming foo is your parameter, it only makes sense that Backbone would apply that URL to fetch a single user, not a collection. 假设foo是您的参数,则只有Backbone将该URL应用于获取单个用户而不是集合才有意义。

I believe your routes are already fine where /api/u should return the collection and /api/u/123 a single user. 我相信您的路由已经很好,其中/api/u应该返回集合,而/api/u/123是单个用户。 What you want is to send extra parameters to /api/u?foo=bar to filter your collection. 您要向/api/u?foo=bar发送额外的参数以过滤您的集合。

Just send these in your .fetch() call in Backbone to get it working. 只需在Backbone中的.fetch()调用中发送它们,即可使其正常工作。 Apply the necessary changes in your controller to filter according to the various parameters possible. 在控制器中应用必要的更改,以根据各种可能的参数进行过滤。

Update 更新资料

Knowing you want posts per user, your question actually has to do nested routes. 知道您想要每位用户发布信息后,您的问题实际上必须进行嵌套路由。 It has already been asked here: Backbone and Rails Nested Routes 已经有人在这里问过: 骨干和Rails嵌套路线

The documentation on Backbone.js is here: http://documentcloud.github.com/backbone/#FAQ-nested 关于Backbone.js的文档在这里: http : //documentcloud.github.com/backbone/#FAQ-nested

To stay a bit more restful , I would define the routes as so: 为了让您更加放松 ,我将路线定义为:

scope '/api' do
  resources :users, only: [], path: 'u' do
    resources :posts, only: :index
  end
end

Which results in: 结果是:

api_user_posts GET /api/u/:user_id/posts(.:format) api/posts#index api_user_posts GET /api/u/:user_id/posts(.:format)api / posts#index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM