10

我有一个非典型的 Rails 应用程序,它需要一个由两个值的复合键索引的表。使用 RESTful 服务添加包含两个值的复合键的正确方法是什么?

如果可能,请指出参考。

4

3 回答 3

4

我花了很多测试才想出一个几乎“优雅”的解决方案:

scope "/users/:key1/:key2" do
  resource :users, :path => "" do
    resources :posts
  end
end

它产生:

    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
于 2013-12-11T16:23:54.870 回答
2

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.

于 2013-06-07T18:42:31.197 回答
0

好吧,这很难说,但使用这样的路线应该是公平和好的。

http://domain/object/:value1/:value2

如果用户可以查看这两个键,则这是迄今为止最简单的方法。如果两个值都是获取对象所必需的,那么这是一个很好的方法。如果只需要一个值,您可以使用主 ID,例如

http://domain/object/:id?value2=...

或类似的东西

http://domain/object/:value1/:value2

其中 value2 是可选参数。

也就是说,其他一切都应该像与其他一切一起工作一样工作。唯一的区别是路由将不仅仅是一个 id。

更多的

另外,我不得不说,人们经常误解休息。Rails 大量使用 CRUD 请求,任何事情都可以很安静。这个想法是有一个 url 代表你试图访问的内容。

看一下这个:

https://en.wikipedia.org/wiki/Representational_state_transfer

如果需要,不要害怕使用 get 参数。主要思想是有一个指向资源的 url 和其他参数可以用来获取特定的东西。

我认为最终解决您问题的真正方法是常识!

于 2013-06-16T22:23:13.970 回答