Всякий раз, когда создается новый пользователь, пользователь получает роль, к которой применяется. Это происходит через метод after_create. Вот метод:Rails, after_create вызывается дважды
def add_user_role
self.roles << Role.find_by_role("user")
end
Однако пользователь дважды выполняет роль. После создания, это происходит:
=> #<ActiveRecord::Associations::CollectionProxy [#<Role id: 21, role: "user", created_at: "2016-10-27 15:13:44", updated_at: "2016-10-27 15:13:44">, #<Role id: 21, role: "user", created_at: "2016-10-27 15:13:44", updated_at: "2016-10-27 15:13:44">]>
irb(main):002:0>
Если я закомментировать команду надстройку, никакой роли не применяется к пользователю:
def add_user_role
# self.roles << Role.find_by_role("user")
end
После создания:
=> #<ActiveRecord::Associations::CollectionProxy []>
Кто-нибудь идея, почему это происходит?
after_create метод находится в User.rb:
class User < ApplicationRecord
after_create :add_user_role
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :directions
has_many :roles, through: :directions
end
private
def add_user_role
self.roles << Role.find_by_role("user")
end
У меня есть два пользовательских контроллеры, вот они:
пользователя контроллера для администратора:
class UsersController < ApplicationController
before_action :authenticate_user!
before_action :current_user_allowed?
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
role = params[:role]
add_user_role(@user,role)
redirect_to root_path
end
end
private
def current_user_allowed?
current_user.roles.each do |role|
if role.role == "superadmin"
return
end
end
redirect_to root_path
end
def add_user_role(user, role1)
user.roles.create(role: role1)
end
def user_params
params.require(:user).permit(:role)
end
контроллер от разработки:
class Users::RegistrationsController < Devise::RegistrationsController
# before_action :configure_sign_up_params, only: [:create]
# before_action :configure_account_update_params, only: [:update]
# GET /resource/sign_up
# def new
# super
# end
# POST /resource
#def create
# super
#end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
#def update
# super
#end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute])
# end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
# end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
Почему ваш 'add_user_role' в вашей модели' User' за пределами определения класса? Я вижу его после 'end', который закрывает класс. – fanta
@fanta Я не знаю, я видел, как другие люди это делают. Но, будь то в классе или вне него, у меня такая же проблема. Есть идеи? – Metaphysiker
он должен быть внутри вашего класса. Не могли бы вы обновить свой пост с помощью определения «ApplicationRecord»?, Что это за класс? Возможно, у вас что-то есть. – fanta