在使用Devise进行Rails应用设置时,我试图为用户提供一种用于更改密码的表单。
我遵循了Devise Wiki上的解决方案3:https://github.com/heartcombo/devise/wiki/How-To:-Allow-users-to-edit-their-password
并因此包含在用户控制器中
class UsersController < Devise::RegistrationsController
def update_password
@user = current_user
if @user.update(user_params)
# Sign in the user by passing validation in case their password changed
bypass_sign_in(@user)
redirect_to root_path
else
render "edit"
end
end
end
routes.rb
devise_for :users,
path: "", path_names: {
sign_in: "login",
sign_out: "logout",
sign_up: "register",
edit: "settings"
},
controllers: {
registrations: "users",
sessions: "users/sessions"
}
resources :users do
patch 'update_password'
end
耙道给了我
user_update_password_path POST (/:locale)/users/:user_id/update_password(.:format)
users#update_password {:locale=>/fr|en|de/}
访问菜单的链接如下:
<%= link_to user_update_password_path(current_user) %>
在浏览器中,该链接将我定向到:
但是我收到路由错误
没有路由与[GET]“ / en / users / 1 / update_password”匹配
当我包装
resources :users do
resources :wishlists
collection do
patch 'update_password'
end
end
要发送到的链接
哪个会导致错误
未定义的局部变量或方法“ user_update_password_path”用于
<#:0x00007f86cfe48f10>是什么意思? user_password_path
但是,铁路路线显示:
update_password_users PATCH (/:locale)/users/update_password(.:format) users#update_password {:locale=>/fr|en|de/}
但链接至
update_password_users_path
导致错误
找不到路径“ / en / users / update_password”的设备映射。 发生这种情况可能有两个原因:
1)您忘记将路线包装在合并范围内。例如:
devise_scope:user做 得到“ / some / route” =>“ some_devise_controller”结束
2)您正在绕过路由器测试Devise控制器。如果是这样的话, 您可以明确告诉Devise要使用哪个映射:
@ request.env [“ devise.mapping”] = Devise.mappings [:user]
我错过了什么?
答案 0 :(得分:0)
首先在解决方案3中说resource
而不是resources
。仔细观察您与下一个之间的差异-
resource :user, only: [:edit] do
collection do
patch 'update_password'
end
end
第二条路线应该直接引向edit_user_path
而不是update_password_user
,因为那是patch
路线。
第三,您必须按照Wiki的建议向控制器添加一个edit
操作。还有行动的形式。
before_action :authenticate_user!
def edit
@user = current_user
end
和app/views/users/edit.html.erb
<%= form_for(@user, :url => { :action => "update_password" } ) do |f| %>
<div class="field">
<%= f.label :password, "Password" %><br />
<%= f.password_field :password, :autocomplete => "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="action_container">
<%= f.submit %>
</div>
<% end %>
您错过了很多东西。尝试再次阅读Wiki。