简体   繁体   中英

Backbone Collection url with dynamic parameters

I'm writing a Rails app with Backbone.js.

In Rails, I have a route in config/routes.rb that takes an argument like this: /api/u/foo . It gets all posts by the argument, in this case foo . The output of this is all posts by foo. Foo is a user, who has many posts.

In Backbone, I need to set the url attribute on the collection to take arguments from the route, like this: /u/foo . I want that to go get /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.

The relevant part of the routes.rb file:

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.

I believe your routes are already fine where /api/u should return the collection and /api/u/123 a single user. What you want is to send extra parameters to /api/u?foo=bar to filter your collection.

Just send these in your .fetch() call in Backbone to get it working. 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

The documentation on Backbone.js is here: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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