tl;博士:
Devise::RegistrationsController 不实例化关联的多态模型,解决这个问题的最佳方法是什么?
设置:
我有一个地址模型,我与不同的实体(例如一个人、一个企业)相关联,因此使用了多态关系:
class Person < ActiveRecord::Base
has_one :address, :as => :addressable
accepts_nested_attributes_for :address # to make fields_for work
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
我使用 Person 模型作为 Devise 模型,但在注册新帐户时遇到了地址对象未实例化或保存的问题。
Person 控制器,据我所知,它已被 Devise RegistrationController(路由:)所取代,它new_person_registration GET /person/sign_up(.:format) devise/registrations#new
有代码来实例化在我开始使用 Devise 之前用来完成这个技巧的各个对象:
class PeopleController < ApplicationController
[...]
def create
@person = Person.new(params[:person])
@person.address = Address.new(params[:address])
[...some checking...]
@person.save
@person.address.save
end
def new
@person = Person.new
@person.address = Address.new
end
end
现在似乎 Devise::RegistrationsController 没有创建 Address 对象。
一种建议的解决方案是使用回调来初始化对象,因此我的人模型具有:
before_create :instantiate_all
before_save :save_all
def save_all
self.address.save
self.save
end
def instantiate_all
if self.address.nil?
self.address = Address.new
end
end
有了这个,我仍然得到
NoMethodError (undefined method `address' for nil:NilClass):
app/models/person.rb:25:in `save_all'
我正在考虑覆盖 RegistrationController 但似乎通过调用super
我将执行相应父方法的整个块,因此将无法插入我想要的操作。
最后,重写控制器,复制它的代码并添加我的代码似乎太错误了,不能成为完成这件事的唯一方法。
我很感激你们的想法。