加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如果关联记录在访问时不存在,如何创建关联记录

发布时间:2020-12-17 02:17:47 所属栏目:百科 来源:网络整理
导读:我该怎么做这个sudo代码? 我想阻止例如“未定义的方法zip_code for nil class”,因为我已经拥有了我们的配置文件的用户.因此,当调用user.profile时,如果它不存在,我想创建它. class User ActiveRecord::Base... # Associations: has_one :profile # example
我该怎么做这个sudo代码?
我想阻止例如“未定义的方法zip_code for nil class”,因为我已经拥有了我们的配置文件的用户.因此,当调用user.profile时,如果它不存在,我想创建它.

class User < ActiveRecord::Base
...
  # Associations:
  has_one :profile


  # example call current_user.profile.zip_code
  def profile
    if self.profile exists <-- use super?
      self.profile
   else
     # create association record and return it
     self.build_profile.save
     self.profile
   end
  end
...
end

解决方法

你可以使用after_initialize回调:

class User
  # ..
  after_initialize do
    self.profile ||= self.build_profile
  end
  # ..
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读