我可以缩小Rails中多态关系检索的类的类型吗?

时间:2009-06-28 12:40:50

标签: ruby-on-rails polymorphic-associations

我在Rails中有多态关系,但在一个特定的使用实例中,我只想检索特定类的记录。

这样做的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

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" ... >]

答案 1 :(得分:0)

rails插件has_many_polymorphs可以很好地适应这个目的。您可以定义“getters”来拉出属于多态关系的特定数据类型。

这有点复杂,但文档可以提供改进。