Rails关联回调(before_add和before_remove)不起作用

问题描述 投票:2回答:1
class User
  has_many :profiles, class_name: "MyClass::Profile",
    foreign_key: "user_id", before_add: :myfn, before_remove: :myfn2, dependent: :destroy

  def myfn(record)
    logger.debug('calling1')
  end

  def myfn2(record)
    logger.debug('calling2')
  end
end

module MyClass
  class Profile
    belongs_to :user
  end
end

注意:通过

添加配置文件

user_instance.profiles.create({profile_data})

也尝试过

user_instance.profiles << profile_instance

删除者

user_instance.profiles.destroy(profile_instance)

这2个关联回调对我不起作用。任何建议都会很棒。

ruby-on-rails callback
1个回答
0
投票

before_add的工作方式与:

user_instance.profiles.create(<profile data>)

注意,它不需要接收Profile实例。这样做会引发ArgumentError错误。

after_add的工作方式与:

user_instance.profiles.destroy(profile_instance)
© www.soinside.com 2019 - 2024. All rights reserved.