I have an atypical Rails application that needs a table to be indexed by a composite key of two values. Which is the correct way using a RESTful service to add a composite key of two values?
If possible, please point to references.
It took to me a lot of tests to come up with an almost "elegant" solution:
scope "/users/:key1/:key2" do
resource :users, :path => "" do
resources :posts
end
end
It produces:
users_posts GET /users/:key1/:key2/posts(.:format) posts#index
POST /users/:key1/:key2/posts(.:format) posts#create
new_users_post GET /users/:key1/:key2/posts/new(.:format) posts#new
edit_users_post GET /users/:key1/:key2/posts/:id/edit(.:format) posts#edit
users_post GET /users/:key1/:key2/posts/:id(.:format) posts#show
PUT /users/:key1/:key2/posts/:id(.:format) posts#update
DELETE /users/:key1/:key2/posts/:id(.:format) posts#destroy
users POST /users/:key1/:key2(.:format) users#create
new_users GET /users/:key1/:key2/new(.:format) users#new
edit_users GET /users/:key1/:key2/edit(.:format) users#edit
GET /users/:key1/:key2(.:format) users#show
PUT /users/:key1/:key2(.:format) users#update
DELETE /users/:key1/:key2(.:format) users#destroy
you can use the gem composite primary keys
, see homepage.
It uses standard RESTful routes and combines the value of multiple attributes in one :id
parameter.
This seems to be a good appraoch, as you still reference the object with its identfier, which is a combination of several attributes in your case.
You may also use this technique without the gem by combining the attributes in to_param
and split then again for searching. It keeps the standard RESTful routes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With