与普通的crud一样,增加 route controller view即可

在书写controller的 时候注意需要什么逻辑,可以进行注释,然后在书写 ,注意语法,参数的变动,URL的跳转。注意这里的编辑,不要根据id进行,因为根据id的话,别人也可以修改自己的,只能根据正确的用户进行判断。

<code class="language-ruby">class ManagerPasswordsController &lt; ApplicationController
before_action :authenticate_manager!
before_action :save_log
def edit_password
@manager = @current_manager
end 
def update_password
@manager = Manager.find params[:id]
#判断密码是否正确,是否有修改权限,密码正确,可以进行修改
#if params[:old_password] == @manager.password
if @manager.valid_password?(params[:old_password])
#valid_password?('password123')
#判断新密码是否输入一致,输入一致,保存新密码
if params[:new_password] == params[:repeat_new_password]
@manager.password = params[:new_password]
@manager.save!
redirect_to '/', notice: '操作成功'
else
redirect_to edit_password_manager_passwords_path, notice: '密码输入不一致'
end 
else
redirect_to edit_password_manager_passwords_path, notice: '密码错误'
end 
end 
end
~    

在routes文件增加路由,需要的仅仅是编辑和更新页面,因为密码页面不需要显示,密码都是在数据库加密显示的,显示也不起作用。

<code class="language-ruby">resources :manager_passwords do
11     collection do
12       get :edit_password
13       post :update_password
14     end 
15   end

视图页面就是普通的页面,注意是post不是put,还有就是form表单的首行,地址要写好。

<code class="language-html">&lt;h3&gt;修改密码&lt;/h3&gt;
&lt;%= form_tag update_password_manager_passwords_path(id: @manager.id), method: 'post' do %&gt;
&lt;p&gt;原密码:&lt;%= password_field_tag :old_password, '', class: 'form-control', style: 'display: inline; width: 200px' %&gt;&lt;/p&gt;
&lt;p&gt;新密码:&lt;%= password_field_tag :new_password, '', class: 'form-control', style: 'display: inline; width: 200px' %&gt;&lt;/p&gt;
&lt;p&gt;确认新密码:&lt;%= password_field_tag :repeat_new_password, '', class: 'form-control', style: 'display: inline; width: 200px' %&gt;&lt;/p&gt;
&lt;%= submit_tag "确认修改", class: 'btn btn-primary' %&gt;
&lt;% end %&gt;
&lt;ul class="nav navbar-nav px-3" style='float:right'&gt;
&lt;li class="nav-item text-nowrap"&gt;
&lt;%= link_to "修改密码", "/manager_passwords/edit_password", class: 'nav-link' %&gt;
&lt;/li&gt;
&lt;/ul&gt;