I have a polymorphic relationship in Rails, but in one particular instance of use, I'd only like to retrieve records for a specific class.
What's the best approach to do this?
I have a polymorphic relationship in Rails, but in one particular instance of use, I'd only like to retrieve records for a specific class.
What's the best approach to do this?
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
class Person < ActiveRecord::Base
has_many :addresses, :as => :addressable
end
class Company < ActiveRecord::Base
has_many :addresses, :as => :addressable
end
>> c = Company.create(:name => "WidgetCo")
>> p = Person.create(:name => "John Smith")
>> a1 = Address.create(:street => "123 Foo ST", :city => "Barville", :state_code => "MT", :zip_code => "12345", :addressable => p)
>> a2 = Address.create(:street => "321 Contact RD", :city => "Bazburg", :state_code => "MT", :zip_code => "54321", :addressable => c)
>> Address.all(:conditions => { :addressable_type => Person.class_name })
=> [#<Address id: 1, street: "123 Foo ST" ... >]
The rails plugin has_many_polymorphs can suit this purpose fairly well. You can define "getters" to pull specific data types out that are part of a polymorphic relationship.
It is somewhat complicated and the documentation could afford to improve however.