尽管在这里查看了一些关于rails中的空对象的答案,但我似乎无法让它们工作。Rails中关联的空对象模式
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,这样才会在读取时发生,而不是在初始创建对象时发生。