Rails: URL/path with parameters

后端 未结 5 747
野性不改
野性不改 2021-02-03 18:47

I would like to produce a URL as

/swimming/students/get_times/2013-01-01/2013-02-02

from this route

get_class_swimming_students         


        
相关标签:
5条回答
  • 2021-02-03 18:50
    get_class_swimming_students_path('2013-01-01', '2013-02-02')
    

    In Rails, URL parameters are mapped to the router in the precise order in which they are passed. Consider the following:

    # rake routes
    my_route GET    /my_route/:first_param/:second_param/:third_param(.:format)
    
    # my_view.html.erb
    <%= link_to('My Route', my_route_path('first_param', 'second_param', 'third_param') %>
    #=> <a href="/my_route/first_param/second_param/third_param">My Route</a>
    

    Consider also the following case where foo and bar are static parameters positioned between dynamic parameters:

    # rake routes
    my_route GET    /my_route/:first_param/foo/:second_param/bar/:third_param(.:format)
    
    # my_view.html.erb
    <%= link_to('My Route', my_route_path('first_param', 'second_param', 'third_param') %>
    #=> <a href="/my_route/first_param/foo/second_param/bar/third_param">My Route</a>
    

    In the final example, arguments will appear as URL parameters in the order in which they were passed, but not necessarily in the same sequence.

    EDIT:

    The following syntax is equivalent to the first snippet. The primary difference is that it accepts arguments as named parameters, rather than in the order they're passed:

    get_class_swimming_students_path(:start_date => '2013-01-01', :end_date => '2013-02-02')
    
    0 讨论(0)
  • 2021-02-03 18:57

    For any path you can pass params like

    get_class_swimming_students_path(:params1 => value1, :params2 => value2)
    

    And In controller you can simply access those passed params as usual

    0 讨论(0)
  • 2021-02-03 19:00

    in rails 4, type less with:

    get_class_swimming_students_path(params1: value1, params2: "value2")
    

    where value1 is a method and value2 is a string

    0 讨论(0)
  • 2021-02-03 19:03

    Try to use that

    get_class_swimming_students_path(:start_date => "2013-01-01", :end_date => "2013-02-02")
    
    0 讨论(0)
  • 2021-02-03 19:14

    You can also combine named parameters and not named parameters like this:

    get_class_swimming_students_path('2013-01-01', '2013-02-02', gender: 'M')
    
    0 讨论(0)
提交回复
热议问题