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

ruby-on-rails-3 – Rails中关联的空对象模式

发布时间:2020-12-17 03:15:55 所属栏目:百科 来源:网络整理
导读:尽管在这里看到一些关于轨道中的Null对象的答案,我似乎无法让它们工作. class User ActiveRecord::Base has_one :profile accepts_nested_attributes_for :profile def profile self.profile || NullProfile #I have also tried @profile || NullProfile #bu
尽管在这里看到一些关于轨道中的Null对象的答案,我似乎无法让它们工作.

class User < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile

  def profile
    self.profile || NullProfile #I have also tried
    @profile || NullProfile #but it didn't work either
  end
end

class NullProfile
  def display #this method exists on the real Profile class
    ""
  end
end

class UsersController < ApplicationController
  def create
    User.new(params)
  end
end

我的问题是在用户创建时,我为配置文件传递了适当的嵌套属性(profile_attributes),最后我的新用户使用了NullProfile.

我猜这意味着我的自定义配置文件方法在创建时被调用并返回NullProfile.我如何正确地执行此NullObject,以便这仅在读取时发生,而不是在对象的初始创建时发生.

解决方法

我完全通过了,我想要一个干净的新对象,如果它不存在(如果你这样做就是这样object.display不错,也许object.try(:display)更好)这也是我找到了什么:

1:alias / alias_method_chain

def profile_with_no_nill
  profile_without_no_nill || NullProfile
end
alias_method_chain :profile,:no_nill

但是由于alias_method_chain正在被弃用,如果你保持在边缘,你必须自己手动做模式… The answer here似乎提供更好,更优雅的解决方案

2(答案简化/实用版):

class User < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile

  module ProfileNullObject
    def profile
      super || NullProfile
    end
  end
  include ProfileNullObject
end

注意:您执行此操作的顺序(在链接的答案中解释)

你试过的:

当你做到了

def profile
  @profile || NullProfile
end

它不会像预期的那样表现,因为协会被懒惰地加载(除非你告诉它:在搜索中包含它),所以@profile是nil,这就是为什么你总是得到NullProfile

def profile
  self.profile || NullProfile
end

它会失败,因为该方法正在调用自身,所以它就像一个递归方法,你得到SystemStackError:堆栈级别太深

(编辑:李大同)

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

    推荐文章
      热点阅读