get 'users/:id/edit/settings' => 'users#account'
在link_to
中引用此路徑的乾燥方法是什麼?這條路線的路徑是什麼?
作爲一個方面說明,我用'users/:id/edit'
編輯名稱/位置/年齡等,我使用上面的路線來編輯密碼和電子郵件,因爲我要強制用戶authenticate
他們:current_password
編輯這些更敏感屬性之前。我提到這只是爲了確保我的路由邏輯是正確的。
get 'users/:id/edit/settings' => 'users#account'
在link_to
中引用此路徑的乾燥方法是什麼?這條路線的路徑是什麼?
作爲一個方面說明,我用'users/:id/edit'
編輯名稱/位置/年齡等,我使用上面的路線來編輯密碼和電子郵件,因爲我要強制用戶authenticate
他們:current_password
編輯這些更敏感屬性之前。我提到這只是爲了確保我的路由邏輯是正確的。
變化:
get 'users/:id/edit/settings' => 'users#account', as: :edit_user_settings
,然後你可以參考它:
link_to edit_user_settings_path(@user)
只需運行rake routes
,您將看到您在應用中的所有路線。這應該是它最右邊
rake routes
將可能給你一個路徑類似users_path
你可以鏈接到使用類似的東西 <%= link_to 'Users', users_path(@id) %>
您可以使用as:
選項來設置一條命名路線。
不過,我會與傳統的軌道線路設置它:
Rails.application.routes.draw do
resources :users do
resource :settings, only: [:edit, :update], module: :users
end
end
這將創建一個慣用正確REST風格的路線。
使用單數resource
將創建不帶id參數的路由。此外,您應該只將名稱:id
用於路線中最右邊的動態細分,以避免違反最少突擊的原則。
rake routes
會告訴你以下途徑:
Prefix Verb URI Pattern Controller#Action
edit_user_settings GET /users/:user_id/settings/edit(.:format) users/settings#edit
user_settings PATCH /users/:user_id/settings(.:format) users/settings#update
PUT /users/:user_id/settings(.:format) users/settings#update
...
作爲一個方面說明,我使用「用戶/:ID /編輯」編輯名稱/位置/年齡等 ,我現在用的是上面的路由來編輯密碼和電子郵件,因爲我 希望強制用戶在編輯這些更敏感的屬性之前驗證他們的:current_password 。我提到這只是爲了讓 確定我的路由邏輯是正確的。
您的路線不會強制執行此授權問題。
相反,你應該做一次檢查在你的控制器:
# app/models/users/settings_controller.rb
class Users::SettingsController
before_action :set_user
before_action :check_password, except: [:edit]
def edit
# ...
end
def update
# ...
end
private
def set_user
@user = User.find(params[:user_id])
end
def check_password
# this is an example using ActiveModel::SecurePassword
unless @user.authorize(params[:current_password])
@user.errors.add(:current_password, 'must be correct.')
end
end
end
'你的路線絕不會強制執行此授權concern.'是的,我知道。我的意思是你在關於慣用正確路線的答案的前半部分提到的。乾杯! –