这条路线的路径是什么?
问题描述:
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.'是的,我知道。我的意思是你在关于惯用正确路线的答案的前半部分提到的。干杯! –