如果要用controller與action來建立path,可以用Rails.application.routes.url_helpers.url_for,範例如下:
Rails.application.routes.url_helpers.url_for {
controller: 'admin/accounts',
action: 'edit',
id: '8x5jg5sevpl0d4bo2raa1',
num: '123',
only_path: true
}
上面範例會生出path如下:
/admin/accounts/8x5jg5sevpl0d4bo2raa1/edit?num=123
如果沒有加上only_path: true
,則必須要加上host
這個參數來指定host的位址。
Rails.application.routes.url_helpers.url_for {
controller: 'admin/accounts',
action: 'edit',
id: '8x5jg5sevpl0d4bo2raa1',
num: '123',
host: 'www.example.com'
}
當初在找解法的時候花了很多時間,最主要的原因是在rails中有太多叫url_for
的method了,搞的我很亂啊。原本我要用ActionView::RoutingUrlFor#url_for
,這個method也是view中呼叫url_for預設的method,結果發現它會自動將目前的網址參數也幫你加進去,這樣反而會在某些情況造成No route的error。後來trace了url_for的source(ActionView::RoutingUrlFor#url_for -> ActionDispatch::Routing::UrlFor -> ActionDispatch::Routing::RouteSet)
才找到有Rails.application.routes.url_helpers.url_for可以用。