如果请求包含查询字符串,则路由到单独的操作

Air*_*219 2 ruby ajax ruby-on-rails

我想知道我是否可以设置路由,以便带参数的show route转到另一个方法,当它没有参数时返回show方法.

get fruits/:id   fruits#show 
Run Code Online (Sandbox Code Playgroud)

get fruits/id?market=XXX     fruits#market 
Run Code Online (Sandbox Code Playgroud)

我想这样做,因为我想通过ajax重新加载该页面,我做了一个popstatus来添加该URL.用这种方式使这个工作很好

Sub*_*ial 5

使用路线约束.

get 'fruits/:id', to: 'fruits#market', \ 
                   constraints: ->(request) { request.query_parameters.present? }

get 'fruits/:id', to: 'fruits#show'
Run Code Online (Sandbox Code Playgroud)

您还可以检查是否存在特定参数,例如market:

get 'fruits/:id', to: 'fruits#market', \ 
          constraints: ->(request) { request.query_parameters[:market].present? }
Run Code Online (Sandbox Code Playgroud)