Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails RESTful routes with a composite key

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.

like image 886
fotanus Avatar asked Jun 07 '13 16:06

fotanus


2 Answers

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
like image 172
fguillen Avatar answered Nov 18 '22 09:11

fguillen


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.

like image 22
Martin M Avatar answered Nov 18 '22 09:11

Martin M