ActiveRecord callbacks? Nah, extend associations!

In the URUG (Utah Ruby User Group), there was discussion about the proper use of ActiveRecord callbacks on the mailing list. Mike Moore, the organizer of MountainWest RubyConf and the Ruby Web Conference, shared some great insights with the rest of us. See the original discussion for more detail.

Mike Moore shared the approach of extending ActiveRecord associations as an alternative that, in many cases, may provide a more appropriate solution.

What does that look like? This is an example for an alternative to an after_create callback.

  class Project < ActiveRecord::Base
    has_many :iterations do
      def build_next
        # Build a new iteration and set the start date.
      end

      def create_next
        next = build_next
        next.save
        next
      end
    end
  end

And then you can call it as easily as this.

  project = project.find 1234
  next = project.iterations.create_next

Now the Iteration model isn’t responsible for knowing how to set the desired start date. And you aren’t adding that code to the Project either. Its cleanly isolated into the association.

When the code to add is more complicated, extract it to a module and “extend” the association.

  module NextIteration
    def build_next
      # Mind bending logic here
    end

    def create_next
      # ditto
    end
  end

  class Project < ActiveRecord::Base
    has_many :iterations, :extend => NextIteration
  end

This keeps the model’s association area nice and clean.

Now, why would we want to avoid callbacks? Mike elaborates with this:

AR callbacks are problematic because it affects every instance of your model, not to mention being a bit magical and indirect. I’m of the opinion that the approach doesn’t scale well for business logic like you are using them for. Suppose your application changes and you don’t want every Iteration to run that code when created. Or are migrating data and want to use those models but don’t want the callbacks. Or, you add someone new to the project and they are unaware of the behavior.

But don’t take my word for it. I suggest googling for “activerecord callbacks” and see how many blog entries are positive vs. negative.

I try to favor explicit over magical. But I have a deep resentment for overly wordy code or shoving logic where it doesn’t belong. Luckily Rails is designed well enough that it gives you many ways to solve this issue.

Mike later elaborates on when he feels AR callbacks are appropriate:

The question remains: then what are AR callbacks good for? They are good for orthogonal side effects. Logic that is outside of the main flow of your application. But the key phrase is “side effects”. Things like logging. Or event notifications. Secondary systems that don’t block. If your logging or eventing systems suddenly crashed your application should still continue to work, right?

Learning all this Ruby goodness makes me happy. :) I was also surprised to find in the APIDock page, that it has been available in Rails for a long time! That’s nice since I actively work in projects on different versions of Rails.

Refer to the Rails docs here or here for more info.

"So in this material world there is ādi, ādy-anta, beginning and ending. But Kṛṣṇa has no beginning or end. The material… Therefore Kṛṣṇa is not material. Urugāya. Kṛṣṇa is urugāya. Uru means He is exalted with nice, many, many ślokas, gāya. Gāya means songs, poetry. Uru. We cannot imagine. Uru-gāya. Just like in the Brahma-saṁhitā: yasyaika-niśvasita-kālam athāvalambya jīvanti loma-vilajā jagad-aṇḍa-nāthāḥ [Bs. 5.48]. Loma-vilajā jagad-aṇḍa-nāthāḥ. So this jagad-aṇḍa-nāthāḥ, mean Brahmā… Jagad-aṇḍa. Āṇḍa means egglike, egg-shaped, this Brahmāṇḍa or this universe. And there are jagad-aṇḍa-nāthāḥ, plural number. So in each universe there is a chief living entity. He is called Brahmā because Brahmā is created first. So that Brahmā, there are millions of universes, and there are millions of Brahmās and millions of Śiva and other demigods. Each Brahmā is full with all different types of living entities. But such Brahmās, where they are being born? Not only Brahmā, the brahmāṇḍa. Yasyaika-niśvasita-kālam athāvalambya jīvanti. Niśvasita-kāla. Just like we exhale and inhale. A minute… Or not minute even. A second. Within a second we exhale and inhale so many times. So similarly, Viṣṇu, Mahā-Viṣṇu, He is also exhaling and inhaling. But during that period so many brahmāṇḍas are coming and so many brahmāṇḍas disappear… Ādy-antavanta, beginning and… But this Mahā-Viṣṇu, who is this Mahā-Viṣṇu? Yasyaika-niśvasita-kālam athāvalambya jīvanti loma-vilaja jagad-aṇḍa-nāthāḥ, viṣṇur mahān sa iha yasya kalā-viśeṣo [Bs. 5.48]. This Mahā-Viṣṇu, from whose breathing so many brahmandas and Brahmas are coming and going, that Mahā-Viṣṇu’s one second just imagine, how many million millions of years. So this is the description of Mahā-Viṣṇu. Then Mahā-Viṣṇu is also partial incarnation of Sankarsana; the Sankarsana is also emanation from Nārāyaṇa; and Nārāyaṇa is also a emanation from the first Catur-vyūha Saṅkarṣaṇa. This Saṅkarṣaṇa is expansion of Baladeva, and Baladeva is the immediate expansion of Kṛṣṇa. Therefore come to the Kṛṣṇa. So ādy-antavanta."

-Srila Prabhupada
SB 7.9.49 lecture
Vrndavana
April 4, 1976

Srila Prabhupada opens my eyes. I’won’t be able to convey the peace He brings to my spiritual eyes with this knowledge. I remain eternally grateful for the chance to hear Him in this realm. All Glories to His Divine Grace A.C. Bhaktivedanta Swami Prabhuapda!

Imagine when you find your soulmate, your heart starts got glow red. Send me “♥” for my muse’s reaction to it happening when our muses meet.

The Altmer walked walked down the stairs and into the Arcanium, a rather bored expression on his face. While he enjoyed his time in the College’s library well enough, the odds of being there alone were never very high (if for no other reason than Urug constantly checking up on him to make sure the books stayed in pristine condition or weren’t stolen).

He rounded the corner, intent on heading to his most favorite book shelf, only to bump into the womer. He fell to the ground due to the force of their collision. “Now see here! You should-” Ahlynn cut himself short as he noticed the glow coming from her chest. Prying his eyes away from the warm glow coming from her heart, he looked down at his own chest to see a glow coming from his own heart. “Oh gods-I-I…oh gods!”

I LOST MY FLASHDRIVE 

i don’t even have a gif to show how upset I am. I have another flash drive but it doesn’t have anything on it and that one had like TWO YEARS of my crap saved on it SHOOT.

Text
Photo
Quote
Link
Chat
Audio
Video