hoyhoy hoyhoy - 6 months ago 10
Ruby Question

In Ruby on Rails, how do I make a polymorphic model associate to a namespaced model?

I have the following models.

# app/models/domain/domain_object.rb
class Domain::DomainObject < ActiveRecord::Base
has_many :links_from, :class_name => "Link", :as => :from, :dependent => :destroy
end

# app/models/link.rb
class Link < ActiveRecord::Base
belongs_to :from, :polymorphic => true
belongs_to :object_value, :polymorphic => true
end


Problem is, when I do the following, the from_type doesn't prefix the Domain namespace to the model e.g.

Domain::DomainObject.all(:include=> :links_from )


That causes the following SELECT:

SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'DomainObject')


The query should be:

SELECT `links`.* FROM `links` WHERE (`links`.`from_id` IN (5,6,12,13,18,24,25,27,29,30,31,32,34,35,39) and `links`.`from_type` = 'Domain::DomainObject')


because Rails automatically saves the model with the namespace.

I've seen a few recommendations on Rails sites about doing something like this:

belongs_to :from, :polymorphic => true, :class_name => "Domain::DomainObject"


However, that doesn't appear to work either.

So, is there a better way to do this? Or is this not supported?

Answer

To fix this, I did a include Domain in the DomainObject model and set ActiveRecord::Base.store_full_sti_class = true in config/environment.rb.