Rails callbacks fail when creating records differently

This is my User model and its Subscription :

 # app/models/user.rb class User < ActiveRecord::Base has_many :subscriptions, :before_add => :cancel_subscriptions! def cancel_subscriptions!(new_subscription=nil) subscriptions.each(&:cancel!) end end # app/models/subscription.rb class Subscription < ActiveRecord::Base belongs_to :user end 

so when i do some_user.subscriptions.create it does a callback :cancel_subscriptions! and then I'm happy. But then I Subscription.create :user => some_user callback does not seem to be called, and I'm sad, so very, very sad.

Is there a way to make sure that the callback is executed whenever a Subscription associated with User ?

PD: I would really like not to write :before_create in my Subscription model, because I think that canceling all signatures should be User responsibility of the model.

+4
source share
1 answer

Technically, the option is :inverse_of for belongs_to , which should handle this situation. In particular, let the other side of the association be aware of the changes on this side. But this only works if the other side has_one . This is not clear from the documentation, but you can see the source .

So now there is no way to make it work automatically.

Note about PD: you really want to transfer subscription functionality from the user model. Managing subscriptions in a user model increases connectivity. And since you have a subscription model, you still do this work and manage subscriptions for one user. Also, before_add not suitable for managing subscriptions. You perform destructive actions in hook_that before any resource is saved. That is, you can cancel all subscriptions and that your new subscription has not passed verification. Thus, you lost your previous subscription (you don’t know which one was active before), and you have an invalid new one that cannot be saved.

+2
source

Source: https://habr.com/ru/post/1369084/


All Articles