我有一个相当困难的问题,我只想在他们提交当前密码时更新用户配置文件。我没有使用设备。这里的另一篇文章在堆栈溢出并没有真正帮助我。 这是我的用户控制器代码:
class UsersController < ApplicationController
def new
@user = User.new
end
def show
@user = User.find(params[:id])
@user_posts = @user.posts if @user
if @user
if @user_posts
render 'show.html'
else
render 'show.html'
end
else
render file: 'public/404.html', status: 404, formats: [:html]
end
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to root_path
flash[:notice] = "Successfully Signed up :-)"
else
redirect_to signup_path
flash[:notice] = "You didn't sign up successfully :-("
end
end
def edit
@user = User.find(params[:id])
if current_user.id = @user.id
render 'edit'
else
redirect_to @user
end
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:notice] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
:password == :password_confirmation
private
def user_params
params.require(:user).permit(:user_name, :email, :password, :password_confirmation)
end
end
这是我的user.rb:
class User
has_secure_password
has_many :posts
has_many :comments
def admin?
self.role == 'admin'
end
def moderator?
self.role == 'moderator'
end
end
请帮助,因为我已经使用了很长时间了。此处有关此主题的其他解决方案在堆栈溢出时无效。
答案 0 :(得分:1)
一种方法是使用virtual attributes
class User < ActiveRecord::Base
attr_accessor :current_password
end
将current_password
attribute
添加到form
作为text_field
input
def update
@user = User.find params[:id]
if @user.authenticate(update_params[:current_password])
# update the user
# maybe check if the data are valid
@user.update(update_params)
else
flash[:warning] = "Please provide your password"
@user.errors.add :current_password, "invalid"
render :edit
end
end
def update_params
params.require(:user).permit(:current_password, :email)
end
答案 1 :(得分:0)
首先,您的edit
操作存在问题:
current_user.id = @user.id
将@user.id
分配给current_user.id
- 您希望==
测试它是否是正确的User
。您应该对update
进行类似的检查,并可能将其提取到before_action
,以便您可以轻松地将其应用到任何您想要的位置。
要检查密码是否存在,请将其与任何其他字段一样添加到表单中,然后将其从params
中取出以进行验证。这看起来像这样:
class UsersController < ApplicationController
def update
encrypted = encrypt(params[:password]) # Using whatever your mechanism is
if encrypted == @user.encrypted_password
# Update the user
else
flash[:notice] = 'Password is required to update user information.'
redirect_to edit_user(path(@user))
end
end
end