【问题标题】:Nested model not available in Devise views嵌套模型在设计视图中不可用
【发布时间】: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


    【解决方案1】:

    这个答案真的很晚,但我发现如果我覆盖整个控制器操作“new”(而不是用“super”将其中的一些委托给父级),那么我可以正确构建资源。原因是“超级”在将控制权交还给您的自定义控制器方法之前呈现视图。长话短说……

    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
    

    应该很好用……至少它对我有用。无论如何,你的代码让我开始走上正轨。

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多