代码之家  ›  专栏  ›  技术社区  ›  sarunw

如何寻找多态关系

  •  1
  • sarunw  · 技术社区  · 15 年前
    class Item < ActiveRecord::Base
    belongs_to :rulable, :polymorphic => true
    end
    class foo < ActiveRecord::Base
    has_many :items, :as => rulable
    end
    class bar < ActiveRecord::Base
    has_many :items, :as => rulable
    end
    

    寻找FOO物品的最佳方法是什么?我目前正在使用类似的功能:

    f = Foo.find 1
    Item.find_by_rulable_id_and_rulable_type(f, 'Foo')
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   EmFi    15 年前

    以下内容在语义上是等价的,并且更容易阅读和输入。

    f = Foo.find 1
    f.items