0
votes

I have two kinds of classes, one of which belongs_to the other kind, and one of which polymorphically belongs to the other kind.

class Term < ActiveRecord::Base
  belongs_to :reference, :polymorphic => true
end

class Course < ActiveRecord::Base
  belongs_to :term
end

class Career < ActiveRecord::Base
  belongs_to :term
end

The relationships are belongs_to because I want fast access in both directions. I'm under the impression that the has_one relationship would be slower because you would have to query the opposite table to search for a matching _id.

Right now, when I create a course c, I run an after_save method which creates a term t such that c.term = t and t.reference = c. This seems like kind of a hack though... is there any way to automatically tell rails that this relationship exists and that setting c.term = t should automatically make t.reference = c?

I know that with polymorphic associations you can specify the :as attribute (see the API), but it looks like this doesn't work for belongs_to.

  class Asset < ActiveRecord::Base
    belongs_to :attachable, :polymorphic => true

    def attachable_type=(sType)
       super(sType.to_s.classify.constantize.base_class.to_s)
    end
  end

  class Post < ActiveRecord::Base
    # because we store "Post" in attachable_type now :dependent => :destroy will work
    has_many :assets, :as => :attachable, :dependent => :destroy
  end
1

1 Answers

1
votes

Yeah, you're not really meant to do bi-directional belongs_to associations. As such, when you add polymorphicality (is that really a word?) into the equation, it will break.

The relationships are belongs_to because I want fast access in both directions. I'm under the impression that the has_one relationship would be slower because you would have to query the opposite table to search for a matching _id.

I don't see why you'd want to do this. If you're really concerned with speed, you can simply index the foreign_key column(s) on the table that belongs_to. The speed difference should be negligible.