我可以缩小类在Rails的多形态关系检索到的类型?
-
20-08-2019 - |
题
我在Rails的多态的关系,但在使用中的一个特例,我只希望检索记录特定类。
什么是做到这一点的最好办法?
解决方案 2
轨道插件has_many_polymorphs能适合此目的相当好。可以定义“吸气剂”拉那是一个多态关系的一部分特定的数据类型的。
这是有点复杂,并且文档可以得到然而,以提高
其他提示
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" ... >]
不隶属于 StackOverflow