ruby-on-rails - Profile:Class 的未定义方法“before_action”
问题描述
下午好,美丽的社区,我有以下疑问:即使方法定义明确,我也有这个错误,如果有人可以帮我一把。我希望当用户注册时自动为该用户创建个人资料
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :patients, dependent: :destroy
has_one :profile, dependent: :destroy
after_create :set_profile
def set_profile
self.profile = Profile.create()
end
end
class Profile < ApplicationRecord
before_action :set_profile
belongs_to :user
private
def set_profile
@profile = (current_user.profile ||= Profile.create)
end
end
class ProfilesController < ApplicationController
before_action :set_profile
def show
end
def edit
end
def update
end
private
def set_profile
@profile = (current_user.profile ||= Profile.create)
end
end
解决方案
发生错误是因为您将模型回调与before_action
属于您的 Profile 类的控制器中的回调混合在一起。它不应该是before_action
但before_save
或类似的东西。
在此处查看模型的可用回调列表:https ://guides.rubyonrails.org/active_record_callbacks.html#available-callbacks
如果您的目标是在创建用户后创建个人资料,那么您的User
课程中的代码就足够了。无需在Profile
类中添加另一个回调(当然,如果你想在那里处理其他东西,你当然可以)。
推荐阅读
- animation - Unity 2D 简单方向混合:忽略一个方向
- ios - 使用结构将 JSON 转换为数组
- pycharm - pycharm 不允许在 Windows 上的 virtualenv 解释器上进行选择
- android - 我无法从我的服务器收到任何通知
- php - 尝试在项目上进行 composer install 但出现需求错误消息
- c# - 来自设计环境的 AppConfig
- selenium - InvalidArgumentException ensureCleanSession 是已知的 IEDriverServer 3.12.0 问题还是我错误地实例化它?
- r - 如何在r中合并表中特定列的后续值
- reactjs - 在哪里使用 URL 参数中的值设置反应组件的状态
- php - 捕获后如何访问 PDOException