【问题标题】:Can I narrow down the type of classes retrieved by a Polymorphic relationship in Rails?我可以缩小 Rails 中的多态关系检索到的类的类型吗?
【发布时间】:2009-06-28 12:40:49
【问题描述】:

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

最好的方法是什么?

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案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" ... >]
    

    【讨论】:

    • 嗯,我应该澄清一下。这是一个双面多态关系。我有:用户>权限>角色我想获取用户所属的所有角色,同时删除权限表上的任何其他记录。 User.roles() 我可以去:has_many :roles, :as => :resource, :through => :permission????
    • 如果您的模型设置正确,您也许可以使用 has_many :through 关联。您能详细介绍一下您的模型吗?
    【解决方案2】:

    rails 插件 has_many_polymorphs 可以很好地满足这个目的。您可以定义“getter”来提取属于多态关系的特定数据类型。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2023-04-06
      • 2011-06-09
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多