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类中添加另一个回调(当然,如果您想在那里处理其他东西,您可以这样做)。


以上是Profile:Class的未定义方法“before_action”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>