简体   繁体   中英

Overriding default parameters in Ruby on Rails with URL query strings

This sounds like it should be a simple question, but here's the route:

get 'routes(/:start_system/:end_system(/:result_type))' => 'routes#calculate',
    :defaults => { :start_system => 'Jita', :end_system => 'Renyn', :result_type => 'short', :min_sec => -1.0 }

The defaults are overridden if I give a URL in this form (for example, we can use integers for the systems instead of their names):

host/routes/30000001/30001437

However, I am trying to provide more information in format strings after, which is not working:

host/routes/30000001/30001437?min_sec=0.5

Basically, the default { :min_sec => -1.0 } is never overridden by the format string at the end of the URL. Is this by design?

The defaults option is only working for params, which you explicitly specify in your route.

You could get the behaviour that you need by modifying your route like this:

get 'routes(/:start_system/:end_system(/:result_type)(/:min_sec))' => 'routes#calculate',
    defaults: { start_system: 'Jita', end_system: 'Renyn', result_type: 'short', min_sec: -1.0 }

Another approach which would maintain your design:

  1. Remove default for min_sec from routes.rb .
  2. Implement default in controller:

    def calculate min_sec = params['min_sec'] || -1.0 ... end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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