首页 > 解决方案 > 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

标签: ruby-on-rails

解决方案


发生错误是因为您将模型回调与before_action属于您的 Profile 类的控制器中的回调混合在一起。它不应该是before_actionbefore_save或类似的东西。

在此处查看模型的可用回调列表:https ://guides.rubyonrails.org/active_record_callbacks.html#available-callbacks

如果您的目标是在创建用户后创建个人资料,那么您的User课程中的代码就足够了。无需在Profile类中添加另一个回调(当然,如果你想在那里处理其他东西,你当然可以)。


推荐阅读