Rails - 在删除has_many模型时设置默认关联

时间:2013-07-22 10:20:16

标签: ruby-on-rails activerecord callback associations

我正在尝试做什么 - 我有很多Profile个,其中每个都有User个。{我有一个默认配置文件。我想要做的是在Profile的删除上将用户从已删除的配置文件关联到默认配置文件。做类似的事情:

class Profile
  has_many :users, dependent: :set_default
  def set_default
  #set default value on destroy
  end
end

class User
  belongs_to :profile
end

我该怎么办?
PS。示例代码缩短为仅包含基本信息。

1 个答案:

答案 0 :(得分:1)

您可以覆盖配置文件关联的getter:

def profile
  user.profile_id ? Profile.find(id) : user.default_profile
end

default_profile是您返回默认配置文件的方法。

您也可以使用alias_method

alias_method :original_profile, :profile

def profile
  original_profile || user.default_profile
end