Trying to metaprogram some has_one associations, perplexed

I have not done much metaprogramming, but I thought I would try it on the latest project I’m working on. Actually this isn’t even metaprogramming, probably. I started by defining methods, but then realized I could just define has_one associations.

Basically we have users who can earn badges. (I know about the merit gem but we want to roll our own). Badge is an activerecord class that belongs_to User with all of the badge types subclassed. Single Table Inheritance. For example:

class SignedUpBadge < Badge
class PostedCommentBadge < Badge

So, I thought to generate a has_one association for each badge type. In the User class, if I do this:

[:signed_up_badge, :posted_comment_badge].each do |badgetype|
  has_one badgetype
end

It works fine. But we plan on having probably up to fifty badge types, so I would rather just generate associations from a list of the Badge subclasses. When I do this:

Badge.descendants.each do |badgetype|
  has_one badgetype.name.underscore.to_sym    # not sure to_sym is even necessary
end

none of the associations are there. What am I missing?

It could be related to the load order - none of the subclasses exist yet at the time you try iterate over them.

I wondered about that. Is there a way to create these associations in another way / at a later time? Maybe when the class is instantiated?

By putting this above the block where I’m iterating through badges, it was fixed:

Rails.application.eager_load!

I guess I just needed to get all the classes loaded up.