【发布时间】:2011-05-15 01:34:35
【问题描述】:
我遇到了一个问题,关联在我的视图中不可用。
我的模型是:
:user has_many :subscriptions
:subscription belongs_to :user
我正在使用 Devise 为用户管理身份验证等
我想做的事:在注册过程中创建新用户时,我还想为该用户创建订阅。
由于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,那效果很好。但我认为这种逻辑属于控制器而不是视图,我想知道是什么让我无法将它放在那里。
【问题讨论】:
标签: ruby-on-rails-3 devise nested-forms