Monday, February 7, 2011

Can I narrow down the type of classes retrieved by a Polymorphic relationship in Rails?

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" ... >]
    
    Omega : Mm, I should have clarified. This is a double-sided polymorphic relationship. I have: Users > Permission > Roles I'd like to get all roles a user belongs to, while stripping out any other records on the permission table. User.roles() Can I go: has_many :roles, :as => :resource, :through => :permission????
    Joel Meador : You might be able to use that has_many :through association, if your models are set up properly. Can you go into a little more detail about your models?
  • 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.

    From Omega

0 comments:

Post a Comment