我遇到了在我的视图中不可用的关联问题。在设计视图中无法使用嵌套模型
我的车型有:
:user has_many :subscriptions
:subscription belongs_to :user
我用设计来管理用户
我想什么做认证等:在注册过程中创建一个新用户的时候,我还希望为该用户创建订阅。 由于Devise::RegistrationsController#new
默认情况下不初始化相关的订阅,我已经创建了自己的RegistrationsController
:
class RegistrationsController < Devise::RegistrationsController
def new
super
resource.subscriptions.build
logger.debug resource.subscriptions.inspect
end
end
调试语句有确认一个Subscription
对象创建成功:
[#<Subscription id: nil, user_id: nil, chargify_subscription_id: nil, chargify_product_handle: nil, created_at: nil, updated_at: nil>]
的问题:在视图中,resource.subscriptions
不存在。 如果我在视图中检查resource
,我得到一个User
对象包括所有其自身的属性,但没有关联的(它应该有一个相关的subscriptions
)
debug(resource)
给出如下:
--- !ruby/object:User
attributes:
name:
encrypted_password: ""
created_at:
updated_at:
last_sign_in_ip:
last_sign_in_at:
sign_in_count: 0 last_name:
current_sign_in_ip:
reset_password_token:
current_sign_in_at:
remember_created_at:
reset_password_sent_at:
chargify_customer_reference:
first_name:
email: ""
attributes_cache: {}
changed_attributes: {}
destroyed: false
marked_for_destruction: false
new_record: true
previously_changed: {}
readonly: false
有我错过了一些东西,或者对于Devise使用的防止关联在视图中可用的resource
机制有点奇怪吗?
谢谢!
编辑: 如果我只在我的视图中添加resource.subscriptions.build
,然后再重新生成表单,那可以正常工作。但我认为这种逻辑属于控制器而不是视图,我想知道是什么让我无法将它放在那里。