尽管在这里看到一些关于轨道中的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
Run Code Online (Sandbox Code Playgroud)
我的问题是在用户创建时,我为配置文件传递了适当的嵌套属性(profile_attributes),最后我的新用户使用了NullProfile.
我猜这意味着我的自定义配置文件方法在创建时被调用并返回NullProfile.我如何正确地执行此NullObject,以便这仅在读取时发生,而不是在对象的初始创建时发生.