TL; DR: Strip params
только то, что вы хотите, я называю это user_params
. В действии, которое обрабатывает форму, проверьте, является ли user_params[:password]
пустым, и если она пытается обновить вашу модель @user
с помощью @user.update_without_password(user_params)
, если она не пытается обновить с помощью @user.update(user_params)
. Если применимый запрос на обновление возвращается false
@user.errors
содержит объяснения.
Вот точно, как я решил эту проблему:
Я определил resource
в моем config/routes
файле:
resource :profile
Я сделал контроллер для моего ресурса, который проходит проверку подлинности контроллера ProfilesController < AuthenticatedController
DEViSE в для управления профилями. Контроллер Profiles содержит несколько методов включая user_params
, которые в основном фильтрует params
вниз в белый список:
def user_params
accessible = [
:first_name,
:last_name,
:email,
:password,
:password_confirmation
]
params.require(:user).permit(accessible)
end
и update
, который делает бизнес обработки формы:
def update
# current_user holds the logged in user
@user = current_user
# IF they've left the password field blank,
# AND the devise update_without_password method returns true
# OR IF a full update of user (including password and password_confirmation) returns true
# THEN re-sign them in to flush their session, and redirect them back to their dashboard, and send a success message.
# ELSE re-present the edit form they were just on (there's a handy catcher
# in the edit view script to render the form errors, you can find them on
# @user.errors)
if (user_params[:password].blank? && @user.update_without_password(user_params)) || @user.update(user_params)
sign_in(@user, bypass: true)
redirect_to '/dashboard', notice: 'Your profile changes have been saved.'
else
render 'edit'
end
end
Там же, конечно, скрипт вида (один случай в моем случае - app/views/profiles/edit.html.haml
), который использует form_for
для визуализации формы:
= form_for current_user, as: :user, url: profile_path, html: { class: '' } do |f|
# [f.label, f.text_field, f.password_field, etc...]
Моя модель Пользователь также имеет все Разрабатывают-й благость включены:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :receipts
validate :first_name, presence: true
validate :last_name, presence: true
validate :email, presence: true, email: true
end
Для записи: Это «официальное» решение - https://github.com/plataformatec/devise/wiki/How- To: -Allow пользователей-к-редактировать-их-счет-без предоставления-а-пароль. – lostphilosopher