Nested model not available in view modes

I had a problem with the lack of associations in my views.

My models:

:user has_many :subscriptions :subscription belongs_to :user 

I use Devise to manage authentication, etc. for users

What I would like to do: when creating a new user during the registration process, I also want to create a subscription for this user. Since Devise::RegistrationsController#new does not initialize the associated subscription by default, I created my own RegistrationsController :

 class RegistrationsController < Devise::RegistrationsController def new super resource.subscriptions.build logger.debug resource.subscriptions.inspect end end 

The debug statement there confirms that the Subscription object has been successfully created:

 [#<Subscription id: nil, user_id: nil, chargify_subscription_id: nil, chargify_product_handle: nil, created_at: nil, updated_at: nil>] 

Problem: resource.subscriptions do not exist in view. If I check the resource in the view, I get a User object that includes all its own attributes but has no associations (it must have associated subscriptions )

debug(resource) gives the following:

 --- !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 

Is there something that I am missing, or maybe there is something strange in the resource mechanism used by Devise that does not allow associations to be accessible in the view?

Thanks!

Edit: If I just add resource.subscriptions.build in my opinion, before breaking the form, that would be fine. But I think that this logic belongs to the controller, not the opinion, and I would like to know what prevents me from carrying it.

0
source share
1 answer

This answer is really delayed, but I found that if I redefine the action of the entire controller to β€œnew” (instead of delegating part of it to the parent β€œsuper”), I can build the resource correctly. The reason is that "super" displays the view before passing control back to your custom controller method. Shortly speaking...

 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 

It should work beautifully ... at least for me. In any case, your code launched me on the right track.

+4
source

All Articles