2011-05-15 23 views
0

我遇到了在我的视图中不可用的关联问题。在设计视图中无法使用嵌套模型

我的车型有:

: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,然后再重新生成表单,那可以正常工作。但我认为这种逻辑属于控制器而不是视图,我想知道是什么让我无法将它放在那里。

回答

4

这个答案真的很晚,但我发现如果我重写整个控制器动作“新”(而不是委托给父“超级”),然后我可以正确地建立资源。原因是因为“超级”在将控制交还给您的自定义控制器方法之前呈现该视图。长话短说...

class RegistrationsController < Devise::RegistrationsController 
    def new 
    resource = build_resource({}) # as found in Devise::RegistrationsController 
    resource.subscriptions.build 
    respond_with_navigational(resource){ render_with_scope :new } # also from Devise 
    end 
end 

应该很好地工作......至少它为我做了。无论如何,你的代码让我开始了正确的轨道。