user_path(id)在 Ruby-on-Rails 中,您可以使用for UsersController#show( Official doc )等輔助方法獲取路徑/url 。只要您知道模型和操作,就像這個問題一樣,這很容易。
但是我想為任意模型(例如MyModel或 Controller 和類似的動作)獲取路徑,但我show事先并不知道它們。我該怎么做?
使用 Ruby Object#send,動態編程總是可能的,如下所示,我假設您的應用程式遵循 Rails 約定(請注意,以下代碼段的撰寫方式是路徑助手可以在 Rails 中的任何地方使用,不限于視圖等):
# Suppose the model is expressed as a String instance mdl_name (like "User"),
# ID is mdl_id, and the action is a Symbol instance my_action.
case my_action
when :index
Rails.application.routes.url_helpers.send(
mdl_name.underscore.pluralize '_path')
when :show
Rails.application.routes.url_helpers.send(
mdl_name.underscore '_path', mdl_id)
else
# :new, :edit, ...
end
但這一點都不漂亮。我想有更好的方法嗎?
uj5u.com熱心網友回復:
您正在尋找url_for方法,它是所有路由的 rails 骨架鍵。它可以以多種方式使用:
url_for({}) # current url
url_for(controller: 'user', action: :show, id: model.id) # with a hash
url_for(action: :index) # with a partial hash - it will use current controller (and all other current routing params)
url_for(user) # with a model - this is equivalent of user_path(user.id)
url_for([:admin, user]) # scoped model - equivalent of admin_user_path(user.id)
url_for(company, user) # nested routes, equivalent_of copmany_user_path(company.id, user.id)
還有更多。如果這還不夠,你可以resolve在你的路由檔案中定義你自己的動態路由。
url_for 在 Rails 中到處使用。它被link_to, button_to,form_for等使用redirect_to- 上面列出的所有選項都可以在需要 url 的地方使用:
link_to 'User', @user
redirect_to [:admin, user]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/523780.html
標籤:轨道上的红宝石红宝石路线
