简体   繁体   English

我应该如何使这个路由RESTful?

[英]How should I make this routing RESTful?

For RESTful purpose, I made my routing just like this: 出于RESTful目的,我就像这样做了我的路由:

routes.rb 的routes.rb

match 'shops/:sort/:genre/:area', :to => 'shops#index'  

But what if genre was empty? 但如果类型是空的呢? Isn't it going to redirect to example.com/shops/newest_first//california ? 是不是要重定向到example.com/shops/newest_first//california

How can I solve this kind of routing and parameters problem? 如何解决这种路由和参数问题? Can anyone show me good example? 有人能给我看好榜样吗?

view 视图

<%= form_tag shops_path, :method => :get do %>
    <%= select_tag :sort, options_from_collection_for_select(Sort.all, 'id', 'name', params[:sort]), :prompt => "Newest first" %>
    <%= select_tag :genre, options_from_collection_for_select(Genre.all, 'id', 'name', params[:genre]), :prompt => "all" %>
    <%= select_tag :area, options_from_collection_for_select(Area.all, 'id', 'name', params[:area]), :prompt => "all" %>
<% end %>

Another View 另一种观点

While restful routing is the most intuitive and conventional, it does not always fit our needs. 虽然宁静的路由是最直观和最传统的,但它并不总是符合我们的需求。

In your case I'd suggest using query parameters instead of a strict restful route. 在你的情况下,我建议使用查询参数而不是严格的restful路由。

example.com/shops will receive 3 query parameters: sort , genre and area , so a URL may look like example.com/shops?area=california&sort=newest_first example.com/shops将收到3个查询参数: sortgenrearea ,因此URL可能看起来像example.com/shops?area=california&sort=newest_first

The in the index action of you controller you can query for the existence of these parameters in the following manner: 在您的控制器的索引操作中,您可以通过以下方式查询这些参数的存在:

def index
  if !params[:sort].blank?
    @shops = @shops.sort(params[:sort])
  end
  if !params[:area].blank?
    @shops = @shops.where(:area => params[:area])
  end
  .
  .
  .
end

This way you are well protected against missing parameters in your controller, but still you are able to supply whatever data the user requests. 这样,您可以很好地防止控制器中缺少参数,但您仍然可以提供用户请求的任何数据。

On a side note: be sure to check that the params hash you're using contains only values you are willing to accept. 在旁注:请务必检查您正在使用的params哈希仅包含您愿意接受的值。

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

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